QT两个类之间使用信号槽

在做一些东西的时候,习惯性的引入头文件并且调用,因此出现了很多bug,qt的信号槽机制便可以有效的避免一些问题。

A类

复制代码
#ifndef A_H
#define A_H

#include <QObject>
#include <QDebug>
class A : public QObject
{
    Q_OBJECT
public:
    explicit A(QObject *parent = nullptr);

signals:
   void Asignal(void);
public slots:
   void Aslot(void){
       qDebug()<<"A类的槽函数被调用";

   }

};

#endif // A_H

B类

复制代码
#ifndef B_H
#define B_H

#include <QObject>
#include <QDebug>
class B : public QObject
{
    Q_OBJECT
public:
    explicit B(QObject *parent = nullptr);

signals:
   void Bsignal(void);
public slots:
   void Bslot(void){
       qDebug()<<"B类的槽函数被调用";

   }

};


#endif // B_H

mainwindow

复制代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "a.h"
#include "b.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_2_clicked()
{
    qDebug()<<"PushButton(A>B)";
    A *a = new A;
    B *b = new B;
    connect(a,SIGNAL(Asignal()),b,SLOT(Bslot()));
    emit a->Asignal();

}
void MainWindow::on_pushButton_clicked()
{
    qDebug()<<"PushButton(B>A)";
    B *b = new B;
    A *a = new A;
    connect(b,SIGNAL(Bsignal()),a,SLOT(Aslot()));
    emit b->Bsignal();


}

当点击PushButton(A>B)时,A类发送信号,调用B类的槽函数;

当点击PushButton(B>A)时,B类发送信号,调用A类的槽函数。

相关推荐
o***1114几秒前
智能生成ER图工具。使用 SQL 生成 ER 图:让数据库设计更高效
数据库·sql·oracle
ALex_zry5 分钟前
内核开发者的视角:C与Rust在系统编程中的哲学与实践
c语言·开发语言·rust
u***45166 分钟前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
友友马6 分钟前
『QT』窗口 (二) - 深入剖析 QDialog 对话框机制与内存管理
开发语言·qt
TracyCoder1238 分钟前
Java后端Redis客户端选型指南
java·开发语言·redis
u***42079 分钟前
Spring Data JDBC 详解
java·数据库·spring
筱砚.10 分钟前
【C++——文件操作案例】
开发语言·c++
k***921615 分钟前
深入了解 MySQL 中的 JSON_CONTAINS
数据库·mysql·json
Zfox_17 分钟前
【Go】 协程和 channel
开发语言·后端·golang
小石头 1008618 分钟前
【MySql】CRUD
数据库·mysql·adb