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类的槽函数。

相关推荐
学java的小菜鸟啊9 分钟前
第五章 网络编程 TCP/UDP/Socket
java·开发语言·网络·数据结构·网络协议·tcp/ip·udp
立黄昏粥可温14 分钟前
Python 从入门到实战22(类的定义、使用)
开发语言·python
PerfMan17 分钟前
基于eBPF的procstat软件追踪程序垃圾回收(GC)事件
linux·开发语言·gc·ebpf·垃圾回收·procstat
聆听HJ25 分钟前
java 解析excel
java·开发语言·excel
kgduu28 分钟前
Qt之QFuture理解
qt
溪午闻璐28 分钟前
C++ 文件操作
开发语言·c++
失心疯_202329 分钟前
006.MySQL_查询数据
数据库·sql·mysql·关系型数据库·sqlyog·mysql教程·查询语句
环能jvav大师37 分钟前
基于R语言的统计分析基础:使用SQL语句操作数据集
开发语言·数据库·sql·数据分析·r语言·sqlite
吱吱鼠叔41 分钟前
MATLAB方程求解:1.线性方程组
开发语言·matlab·php
Antonio9151 小时前
【CMake】使用CMake在Visual Studio内构建多文件夹工程
开发语言·c++·visual studio