错误一: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();
}