这篇文章主要介绍“Qt开发如何实现跨窗口信号槽通信”,在日常操作中,相信很多人在Qt开发如何实现跨窗口信号槽通信问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”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_H
mainwindow.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_H
subwindow.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");
}
到此,关于“Qt开发如何实现跨窗口信号槽通信”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。