Qt5 跨窗口信号槽通信

2019-06-12  本文已影响0人  飞扬code

多窗口通信,如果是窗口类对象之间互相包含,则可以直接开放public接口调用,不过,很多情况下主窗口和子窗口之间要做到异步消息通信,就必须依赖到跨窗口的自定义信号与槽。

注意:
1.使用信号与槽机制,一定要是QObject类和QObject派生类才有效,否则该机制是无效的。
2.使用信号与槽机制时,需要在类的头文件的第一行加入Q_OBJECT宏,同时该类最好是QObject的派生类。
3.如果正确使用信号与槽机制,同时没有语法错误;但是编译时仍然报错,这时可以尝试把编译出的build*文件整个删除,然后再次编译。(有时是编译过的build文件对信号与槽机制有影响)

以下是一个简单的示例
子窗口发送信号,主窗口打开子窗口,并创建好信号槽关联,通过信号槽函数传递消息参数
主窗口

#include "mainwindow.h"
#include "subwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle("MainWindow");
    setFixedSize(400, 300);

    // add text label
    label = new QLabel(this);
    label->setText("to be changed");

    // open sub window and connect
    SubWindow *subwindow = new SubWindow(this);
    connect(subwindow, SIGNAL(sendText(QString)), this, SLOT(receiveMsg(QString)));
    subwindow->show(); // use open or exec both ok
}

void MainWindow::receiveMsg(QString str)
{
    // receive msg in the slot
    label->setText(str);
}

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

子窗口

#include "QPushButton"
#include "subwindow.h"

SubWindow::SubWindow(QWidget *parent) : QDialog(parent)
{
    setWindowTitle("SubWindow");
    setFixedSize(200, 100);

    QPushButton *button = new QPushButton("click", this);
    connect(button, SIGNAL(clicked()), this, SLOT(onBtnClick()));
}

void SubWindow::onBtnClick()
{
    // send signal
    emit sendText("hello qt");
}

SubWindow::~SubWindow()
{
    delete ui;
}
image.png image.png
上一篇 下一篇

猜你喜欢

热点阅读