这篇文章主要为大家详细介绍了Qt开发实现跨窗口信号槽通信,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
多窗口通信,如果是窗口类对象之间互相包含,则可以直接开放public接口调用,不过,很多情况下主窗口和子窗口之间要做到异步消息通信,就必须依赖到跨窗口的信号槽,以下是一个简单的示例。
母窗口
mainwindow.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QLabel>#include <QString>classMainWindow : publicQMainWindow{ Q_OBJECTpublic: MainWindow(QWidget *parent = 0); ~MainWindow();privateslots: voidreceiveMsg(QString str);private: QLabel *label;};#endif // MAINWINDOW_H |
mainwindow.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include "mainwindow.h"#include "subwindow.h"MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent){ setWindowTitle("MainWindow"); setFixedSize(400, 300); // add text label label = newQLabel(this); label->setText("to be changed"); // open sub window and connect SubWindow *subwindow = newSubWindow(this); connect(subwindow, SIGNAL(sendText(QString)), this, SLOT(receiveMsg(QString))); subwindow->show(); // use open or exec both ok}voidMainWindow::receiveMsg(QString str){ // receive msg in the slot label->setText(str);}MainWindow::~MainWindow(){} |
子窗口
subwindow.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #ifndef SUBWINDOW_H#define SUBWINDOW_H#include <QDialog>classSubWindow : publicQDialog{ Q_OBJECTpublic: explicitSubWindow(QWidget *parent = 0);signals: voidsendText(QString str);publicslots: voidonBtnClick();};#endif // SUBWINDOW_H |
subwindow.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include "QPushButton"#include "subwindow.h"SubWindow::SubWindow(QWidget *parent) : QDialog(parent){ setWindowTitle("SubWindow"); setFixedSize(200, 100); QPushButton *button = newQPushButton("click", this); connect(button, SIGNAL(clicked()), this, SLOT(onBtnClick()));}voidSubWindow::onBtnClick(){ // send signal emit sendText("hello qt");} |
截图:

基本思路:
1、子窗口发送信号
2、主窗口打开子窗口,并创建好信号槽关联
3、通过信号槽函数传递消息参数
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...










