Qt implements cross-window signal slot communication

For multi-window communication, if the window class objects contain each other, you can directly open public interface calls. However, in many cases, to achieve asynchronous message communication between the main window and sub-windows, you must rely on cross-window signal slots. Below is a simple example.

parent window

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()
{
}

child window

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");
}

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/130643394