1. 程式人生 > >QT入門(三) 多窗體之間的資料傳送

QT入門(三) 多窗體之間的資料傳送

因為我用的是vs的編譯器,所以網上例子很少,結合qt自帶的編譯器的例子,嘗試了半天,實現從子窗體向主窗體的資料傳遞,

主窗體.h程式碼如下

#ifndef ALGORITHMREALIZEPLATFORM_H
#define ALGORITHMREALIZEPLATFORM_H

#include <QtWidgets/QMainWindow>
#include "ui_MainUI.h"
#include "childwindow.h"

class AlgorithmRealizePlatform : public QMainWindow
{
	Q_OBJECT

public:
	AlgorithmRealizePlatform(QWidget *parent = 0);
	~AlgorithmRealizePlatform();
signals:
	void sendsignal(QString);

private:
	Ui::AlgorithmRealizePlatformClass ui;
	childwindow CW;
	QPushButton QPB;
private slots:
	void reshow(QString);
	void test();
};

#endif // ALGORITHMREALIZEPLATFORM_H

主窗體.cpp檔案

#include "algorithmrealizeplatform.h"

AlgorithmRealizePlatform::AlgorithmRealizePlatform(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
    //普通的窗體內部訊號和槽體的連線
	connect(&QPB, &QPushButton::clicked, this, &AlgorithmRealizePlatform::test); 
    //與子窗體的訊號連線      
	connect(&CW, &childwindow::send_data, this, &AlgorithmRealizePlatform::reshow);
}

AlgorithmRealizePlatform::~AlgorithmRealizePlatform()
{
	
}

void AlgorithmRealizePlatform::test()
{
	QString a = "aaaaaaaaaa";
	ui.label->setText(a);
	CW.show();
}

void AlgorithmRealizePlatform::reshow(QString y)
{
	QString a = "aaaaaaaaaa";
	ui.label->setText(y);
	//this->close();
}

 子窗體.h檔案

#ifndef CHILDWINDOW_H
#define CHILDWINDOW_H

#include <QWidget>
#include "ui_childwindow.h"

class childwindow : public QWidget
{
	Q_OBJECT

public:
	childwindow(QWidget *parent = 0);
	~childwindow();
	QString buf;
	
signals:
	void send_data(QString y);

private:
	Ui::childwindow ui;
private slots:
	void on_push_close_clicked();
};

#endif // CHILDWINDOW_H

子窗體.cpp檔案

#include "childwindow.h"

childwindow::childwindow(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
}

childwindow::~childwindow()
{

}

void childwindow::on_push_close_clicked()
{
	buf = ui.label->text();
	emit send_data(buf);    //傳出子窗體訊號
	this->close();
}

參照https://blog.csdn.net/weibo1230123/article/details/79116016改寫的,

這裡,我對connect(sender, SIGNAL(signal), receiver, SLOT(slot))的理解是:

1、sender和receiver分別是訊號端和接收端的QObject的例項化,signal和slot是其中的具體方法

2、需要注意的是signal和slot的引數需要儘量一致吧,不要找麻煩,想繼續的話,轉https://blog.csdn.net/WilliamSun0122/article/details/72810352