在做一些东西的时候,习惯性的引入头文件并且调用,因此出现了很多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类的槽函数。