Qt跨窗口信号槽通信

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Qt跨窗口信号槽通信

踏莎行hyx   2022-05-23 我要评论

多窗口通信,如果是窗口类对象之间互相包含,则可以直接开放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");
}

截图:

基本思路:

1、子窗口发送信号

2、主窗口打开子窗口,并创建好信号槽关联

3、通过信号槽函数传递消息参数

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们