利用QT信号槽在两个类之间传递参数

利用QT信号槽在两个类之间传递参数

在QT项目开发中有时需要通过信号槽完成参数传递,下面通过一段示例代码来演示如何运用QT信号槽在两个类之间完成参数传递。(可以支持在主子窗体类之间传值,非ui类与ui类之间传值)

(1)新建一个Test类,为了使其支持信号槽机制,必须继承自QObject且加上Q_OBJECT宏,否则编译报错: Class contains Q_OBJECT macro but does not inherit from QObject


class Test :public QObject
{
    
    
	Q_OBJECT  //Q_OBJECT宏使得Test类支持信号槽

public:
	Test(QString str) 
	{
    
     
		testStr = str;
	}
	~Test() {
    
    };

	void doTest()
	{
    
    
		emit Test_Signal(testStr); //发射信号
	}

signals:
	void Test_Signal(QString str); //信号函数无返回值,且只声明,不定义。

private:
	QString testStr;
};

(2)新建一个窗体类mainWin,并将Test类中的字符串参数传递到当前窗体类中。QMainWindow继承自QObiect,所以mainWin本身就是QObject对象

#include <QtWidgets/QMainWindow>
#include "ui_mainWin.h"

class mainWin : public QMainWindow
{
    
    
    Q_OBJECT

public:
    mainWin(QWidget *parent = Q_NULLPTR);

public slots:
	void ReceiveStr(QString str);
	void Button_Slot();

private:
    Ui::mainWinClass ui;
	QString myStr;
};


mainWin::mainWin(QWidget *parent)
    : QMainWindow(parent)
{
    
    
    ui.setupUi(this);
	connect(ui.pushButton, &QPushButton::clicked, this, &mainWin::Button_Slot);
}


void mainWin::ReceiveStr(QString str)
{
    
    
	this->myStr = str; //在槽函数中传递参数
}


void mainWin::Button_Slot()
{
    
    
	ui.lineEdit->setText(myStr);
}

(3)在mainWin类和Test类的外部完成参数传递。

#include "mainWin.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    
    
	QApplication::setStyle("fusion");
    QApplication a(argc, argv);
    mainWin w;
   
	Test myTest("xjm"); 
	//细节1:connect函数的第一个(信号发送者)和第三个参数(信号接收者)必须是指针或者	地址,否则编译报错:connect函数没有与参数列表相匹配的重载实例。
	//细节2:必须先连接信号槽,再发射信号,否则连接失败!
	//细节3:信号函数与槽函数的参数类型与个数应该一致,否则连接失败!
	
	//connect(&myTest, SIGNAL(Test_Signal(QString)), &w, SLOT(ReceiveStr(QString)));   //QT4连接方式
	a.connect(&myTest, &Test::Test_Signal, &w, &mainWin::ReceiveStr);                  //QT5连接方式
	myTest.doTest(); //doTest成员函数发送信号,ReceiveStr接收到信号,程序会转入到ReceiveStr函数中去运行
	
	w.show();
    return a.exec();
}

(4)点击传值按钮,界面上显示从Test类中传递到mainWin类中的字符串
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/NEXUS666/article/details/109129609