Qt開發(fā)實(shí)現(xiàn)跨窗口信號槽通信
多窗口通信,如果是窗口類對象之間互相包含,則可以直接開放public接口調(diào)用,不過,很多情況下主窗口和子窗口之間要做到異步消息通信,就必須依賴到跨窗口的信號槽,以下是一個簡單的示例。
母窗口
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ā)送信號
2、主窗口打開子窗口,并創(chuàng)建好信號槽關(guān)聯(lián)
3、通過信號槽函數(shù)傳遞消息參數(shù)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于OpenGL實(shí)現(xiàn)多段Bezier曲線拼接
這篇文章主要為大家詳細(xì)介紹了基于OpenGL實(shí)現(xiàn)多段Bezier曲線拼接,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C++11運(yùn)算符重載和向量類重載實(shí)例詳解(<<,>>,+,-,*等)
這篇文章主要給大家介紹了關(guān)于C++11運(yùn)算符重載和向量類重載的相關(guān)資料,主要包括<<,>>,+,-,*等,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-07-07
搭建C語言開發(fā)環(huán)境(Windows平臺)匯總
本文給大家匯總了5種在WIN平臺下搭建C語言開發(fā)環(huán)境的方法,包括一、在Windows平臺配置GNU環(huán)境,二、使用Sublime Test開發(fā)C語言程序,三、使用VisualStudio開發(fā)C語言程序,四、搭建EclipseCDT集成開發(fā)環(huán)境,五、搭建Clion集成開發(fā)環(huán)境,有需要的小伙伴可以參考下2015-11-11
C++實(shí)現(xiàn)LeetCode(58.求末尾單詞的長度)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(58.求末尾單詞的長度),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

