多线程下的QT界面UI访问及槽函数的连接。

错误一:ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread.
       该错误是由于多线程直接访问非本线程创建的UI所导致的,我的解决办法(个人根据项目需要设定):
       首先我声明了一个我需要操作的控件的全局指针,在这个控件在主线程初始化完成后,我让这个全局指针指向这个控件。我在该控件类自定义了signal和slots,构造函数中做了关联,在其他线程访问时只需要emit相应的signal即可。(注:多线程情况下需要使用信号与槽来实现线程间的ui操作!!!)
如:

emit p_promptMsg->sig_showMsg("请求参数不正确!");


错误二:QObject::connect: Cannot queue arguments of type 'std::string'
       该错误是由于QT的信号与槽函数不支持c++标准库的string类型,同时也不支持自定义struct、class。可以换成QT对应的类型,或者增加:qRegisterMetaType<std::string>("std::string");语句也可以。
相关说明请查询“qt assistant”。

我相关的代码如下:
(1)prompt.h

#pragma once

#include <QDialog>
#include "ui_prompt.h"

class prompt : public QDialog
{
	Q_OBJECT

public:
	prompt(QWidget *parent = Q_NULLPTR);
	~prompt();

	/*
	 * 提示消息展示
	 * @param promptMsg 提示消息内容
	 */
	void showMsg(std::string promptMsg);

private:
	Ui::prompt ui;

signals:
	void sig_showMsg(std::string content);

public slots:
	void on_okButton_clicked();
	void sl_showMsg(std::string content);
};

(2)prompt.cpp

#include "prompt.h"

prompt::prompt(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	qRegisterMetaType<std::string>("std::string");   //非QT的类型都需要在信号槽链接前注册一下,信号与槽不支持非QT类型,结构体,引用也是如此“myStruct&”。
	QObject::connect(this, SIGNAL(sig_showMsg(std::string)),this, SLOT(sl_showMsg(std::string)));
	//QObject::connect(this, &prompt::sig_showMsg, this, &prompt::sl_showMsg);   //该链接方式需要信号与槽函数参数类型数量一致,否则链接失败。
}

prompt::~prompt()
{

}

//只能在同线程使用,异步线程需要使用信号与槽链接方式
void prompt::showMsg(std::string promptMsg)
{
	ui.prompt_Msg->setText(QString::fromLocal8Bit(promptMsg.data()));
	this->show();
}

//其他线程使用
void prompt::sl_showMsg(std::string content)
{
	ui.prompt_Msg->setText(QString::fromLocal8Bit(content.data()));
	this->show();
}

void prompt::on_okButton_clicked() {
	this->close();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楼兰小石头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值