Qt QThread问题使用信号/槽从工人到gui [英] Qt QThread trouble using signal/slot going from worker to gui
问题描述
我有一个QT应用程序,使用QT Creator和伴随它的GUI工具开发。我有一个主线程 TheGui
和一个工作线程,由主线程创建 WorkerThread
(称为<$
I have a QT application that was developed using QT Creator and the GUI tool that accompanies it. I have a main thread, TheGui
and a worker thread that is created by the main thread, WorkerThread
(called thread
).
我遇到的问题是,当我在GUI中创建一个插槽使用
The problem I'm having is when I create a slot in the GUI by using
public slot:
void updateTable(string str);
和信号 void sendList(string str) ;
在工作线程的头文件中,插槽永远不会被调用。我使用
within the header file of the GUI and signal void sendList(string str);
within the header file of the worker thread, the slot never gets called. I connected the two using
connect(&thread, SIGNAL(sendList(string str),
this, SLOT(updateTable(string str)));
类似,除了在工作线程中的槽和来自GUI的信号,它工作正常。我知道从使用调试器的信号sendList确实被调用,它是永远不会进入它。
within the constructor in the GUI cpp file. I did something similar except with the slot in the worker thread and signal from the GUI and it worked fine. I know from using the debugger that the signal sendList is indeed getting called, it is just never going into it.
任何想法?
推荐答案
-
slot在不同的线程,它们之间的连接具有
Qt :: QueuedConnection
类型。对于排队连接,Qt必须能够保存信号参数的副本,
因此,要通知Qt类型是可复制的,你必须使用Qt的元对象系统注册它(参见 QMetaType )如下:
Because the signal and the slot are on distinct threads, the connection between them has the
Qt::QueuedConnection
type. And for queued connections, Qt has to be able to save a copy of the signal parameters, to pass them later to the slot.
So, to inform Qt that the type is copyable, you have to register it with Qt's meta-object system (see QMetaType) like this:
// This macro call should be put in one of your .h files
Q_DECLARE_METATYPE(std::string)
// You should call this function before any (queued)
// signal/slot connection involving the type
qRegisterMetaType<std::string>();
参数名称不应包含在 QObject: :connect
调用,类型名称应该与传递给 Q_DECLARE_METATYPE
的类型名称完全相同:
The parameter name shouldn't be included in the QObject::connect
call, and the type names should be exactly the same as the ones you passed to Q_DECLARE_METATYPE
:
connect(&thread, SIGNAL(sendList(std::string), this, SLOT(updateTable(std::string)));
您也可以使用 QString
或 QByteArray
,而不是 std :: string
,因为这些函数是slot和信号,因此已经是Qt特定的。
You can also use QString
or QByteArray
, which are already registered, instead of std::string
, since these functions are slots and signals and as such are already Qt specific.
这篇关于Qt QThread问题使用信号/槽从工人到gui的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!