Qt開(kāi)發(fā)實(shí)現(xiàn)跨窗口信號(hào)槽通信
多窗口通信,如果是窗口類(lèi)對(duì)象之間互相包含,則可以直接開(kāi)放public接口調(diào)用,不過(guò),很多情況下主窗口和子窗口之間要做到異步消息通信,就必須依賴(lài)到跨窗口的信號(hào)槽,以下是一個(gè)簡(jiǎn)單的示例。
母窗口
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、子窗口發(fā)送信號(hào)
2、主窗口打開(kāi)子窗口,并創(chuàng)建好信號(hào)槽關(guān)聯(lián)
3、通過(guò)信號(hào)槽函數(shù)傳遞消息參數(shù)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C語(yǔ)言驅(qū)動(dòng)開(kāi)發(fā)之內(nèi)核使用IO/DPC定時(shí)器詳解
本章將繼續(xù)探索驅(qū)動(dòng)開(kāi)發(fā)中的基礎(chǔ)部分,定時(shí)器在內(nèi)核中同樣很常用,在內(nèi)核中定時(shí)器可以使用兩種,即IO定時(shí)器,以及DPC定時(shí)器,感興趣的可以了解一下2023-04-04
C++數(shù)據(jù)結(jié)構(gòu)之實(shí)現(xiàn)鄰接表
這篇文章主要為大家詳細(xì)介紹了C++數(shù)據(jù)結(jié)構(gòu)之實(shí)現(xiàn)鄰接表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C語(yǔ)言中volatile關(guān)鍵字的深入講解
在程序設(shè)計(jì)中,尤其是在C語(yǔ)言、C++、C#和Java語(yǔ)言中,使用volatile關(guān)鍵字聲明的變量或?qū)ο笸ǔ>哂信c優(yōu)化、多線(xiàn)程相關(guān)的特殊屬性,這篇文章主要給大家介紹了關(guān)于C語(yǔ)言volatile關(guān)鍵字的相關(guān)資料,需要的朋友可以參考下2021-07-07
C++簡(jiǎn)單實(shí)現(xiàn)的全排列算法示例
這篇文章主要介紹了C++簡(jiǎn)單實(shí)現(xiàn)的全排列算法,結(jié)合實(shí)例形式分析了C++排序操作的實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-07-07

