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

相关推荐
数据知道23 分钟前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
小蒜学长23 分钟前
jsp基于JavaWeb的原色蛋糕商城的设计与实现(代码+数据库+LW)
java·开发语言·数据库·spring boot·后端
zhangfeng113327 分钟前
亲测可用,R语言 ggplot2 箱线图线条控制参数详解,箱线图离散数值控制
开发语言·python·r语言·生物信息
yzx99101328 分钟前
国庆科技感祝福:Python 粒子国旗动画
开发语言·人工智能·python
迪丽热爱36 分钟前
【练】C程序设计-01程序设计和C语言
c语言·开发语言
扶尔魔ocy36 分钟前
【QT常用技术讲解】opencv实现摄像头图像检测并裁剪物体
开发语言·qt·opencv
偷光2 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
DKPT3 小时前
JVM栈溢出和堆溢出哪个先满?
java·开发语言·jvm·笔记·学习
gopyer6 小时前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
ajassi20008 小时前
开源 C++ QT QML 开发(二)工程结构
linux·qt·qml