Qt 信号在多层次对象间传递 多层嵌套类对象之间信号传递

一、先说需求:

可能是五层,或多层,子对象要发信号给第一层,这样,如果正常写很麻烦

二、解决方案:

专门拿 出一个类,做为中转类,中转类为单例;

子类,将信号 发给中转类,中转类,再发给写要的类;

上代码:

中转类:

#ifndef TRANSMITSIGNALS_H
#define TRANSMITSIGNALS_H

#include 

class TransmitSignals : public QObject
{
    Q_OBJECT
public:
    static TransmitSignals &GetInstance();
private:
    TransmitSignals();
     ~TransmitSignals();

    TransmitSignals(const TransmitSignals &) = delete;
    TransmitSignals(const TransmitSignals &&) = delete;
    TransmitSignals &operator=(const TransmitSignals &) = delete;



signals:
    void sigReWriteOffsetRet(bool ret);
    void sigFreedDragRet(bool ret);
    void sigEndFreedDragRet(bool ret);

public slots:
};

#endif // TRANSMITSIGNALS_H

cpp

#include "transmitsignals.h"

TransmitSignals::TransmitSignals( )
{

}

TransmitSignals::~TransmitSignals( )
{

}
TransmitSignals& TransmitSignals::GetInstance()
{
    static TransmitSignals RobotControl;
    return RobotControl;
}

想要上专信号 的对象

#include "form.h"
#include "ui_form.h"
#include "transmitsignals.h"
Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);

    connect(this, SIGNAL(send_test(bool)),&TransmitSignals::GetInstance(), SIGNAL(sigReWriteOffsetRet(bool)) );
}

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

void Form::on_pushButton_clicked()
{
    emit send_test(true);
}

接收信号的对象

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 
#include "transmitsignals.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&TransmitSignals::GetInstance(), SIGNAL(sigReWriteOffsetRet(bool)), this, SLOT(on_test_signal(bool)));
}

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

 void MainWindow::on_test_signal(bool ret)
 {
     qDebug()<<"on_pushButton_clicked";
 }
void MainWindow::on_pushButton_clicked()
{
   mForm.show();
}

这样,不管是多少层,其实和二层没有区别了;

你可能感兴趣的:(QT,qt,开发语言)