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开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值