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

相关推荐
点云SLAM17 分钟前
Boost库中Boost.PropertyTree使用和实战示例
开发语言·c++·josn·boost库·参数读取
lly20240622 分钟前
CSS3 分页技术解析
开发语言
CodeCraft Studio28 分钟前
国产化Excel开发组件Spire.XLS教程:Python将列表导出为CSV文件(含一维/二维/字典列表)
开发语言·python·excel·csv·spire.xls·列表导出为csv
Wang's Blog28 分钟前
MySQL: 基准测试全流程指南:原理、工具(mysqlslap/sysbench)与实战演示
数据库·mysql
TravisBytes32 分钟前
一次 Qt 网络程序诡异崩溃排查:从 Breakpad 堆栈到 lambda 捕获悬空引用
网络·qt·php
q***062932 分钟前
如何在 Windows 上安装 MySQL(保姆级教程2024版)
数据库·windows·mysql
百***069440 分钟前
MySQL 创建新用户及授予权限的完整流程
数据库·mysql
guygg8842 分钟前
Alpha稳定分布概率密度函数的MATLAB实现
开发语言·matlab