这篇文章主要为大家详细介绍了Qt开发实现跨窗口信号槽通信,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
多窗口通信,如果是窗口类对象之间互相包含,则可以直接开放public接口调用,不过,很多情况下主窗口和子窗口之间要做到异步消息通信,就必须依赖到跨窗口的信号槽,以下是一个简单的示例。
母窗口
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QString>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void receiveMsg(QString str);
private:
QLabel *label;
};
#endif // MAINWINDOW_Hmainwindow.cpp
#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()
{
}子窗口
subwindow.h
#ifndef SUBWINDOW_H
#define SUBWINDOW_H
#include <QDialog>
class SubWindow : public QDialog
{
Q_OBJECT
public:
explicit SubWindow(QWidget *parent = 0);
signals:
void sendText(QString str);
public slots:
void onBtnClick();
};
#endif // SUBWINDOW_Hsubwindow.cpp
#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");
}截图:

基本思路:
1、子窗口发送信号
2、主窗口打开子窗口,并创建好信号槽关联
3、通过信号槽函数传递消息参数
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:Qt开发实现跨窗口信号槽通信
基础教程推荐
猜你喜欢
- C语言编程C++旋转字符操作串示例详解 2022-11-20
- C++实战之二进制数据处理与封装 2023-05-29
- C语言实现宾馆管理系统课程设计 2023-03-13
- C++实现ETW进行进程变动监控详解 2023-05-15
- 全面了解C语言 static 关键字 2023-03-26
- centos 7 vscode cmake 编译c++工程 2023-09-17
- [C语言]二叉搜索树 2023-09-07
- [c语言-函数]不定量参数 2023-09-08
- 带你深度走入C语言取整以及4种函数 2022-09-17
- C语言 详解字符串基础 2023-03-27
