[英]Communicate between two qt objects in different threads through slots and signals
[英]Qt: Using signals and slots between two child threads
我是Qt和C ++的新手,我正在嘗試制作一個運行兩個子線程threadA和threadB的程序。 這兩個線程都是在main.cpp中創建的,如下所示:
ThreadA threadA;
threadA.start();
ThreadB threadB;
threadB.start();
然后,兩個線程獨立運行。 我需要使threadA能夠調用threadB中的方法,並在過程中將數據作為參數傳遞。 我已嘗試通過將信號和插槽添加到main.cpp中來使用它:
QThread::connect(&threadA, SIGNAL(mySignal(uint)),
&threadB, SLOT(mySlot(uint)));
其中threadA :: mySignal(uint)在以下位置使用:
//a.h
signals:
void mySignal(unsigned int blah);
//a.cpp
emit mySignal(42);
並且threadB :: mySlot(uint)在b中:
//b.h
public slots:
void mySlot(unsigned int fluff);
//b.cpp
void threadB::mySlot(unsigned int fluff)
{ doStuff(fluff); ... }
該程序編譯並成功運行,但是我在調試日志中從QObject收到了一條消息:
QObject::connect: No such slot QThread::mySlot(uint) in ../Project/main.cpp:42
這意味着編譯器在QThread中尋找mySlot而不是threadB。 誰能告訴我我要去哪里錯了? 任何幫助將不勝感激,如有需要,我可以提供更多詳細信息。
首先是你提到的錯誤
該程序編譯並成功運行,但是我在調試日志中從QObject收到了一條消息:
QObject :: connect:../Project/main.cpp:42中沒有這樣的插槽QThread :: mySlot(uint)
您正在使用mySlot
並定義了MySlot
請返回參考代碼
你寫
QThread :: connect(&threadA,SIGNAL(mySignal(uint)),&threadB,SLOT( mySlot (uint)));
並定義
// bh
public slots:
void MySlot(unsigned int fluff);
您可能在threadb.h
(甚至可能是threada.h
)中缺少Q_OBJECT
宏。
class ThreadB : public QObject
{
Q_OBJECT
...
從文檔: All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.
All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration. They must also derive (directly or indirectly) from QObject.
我還假設您已將QThread
子類化。 您應該知道QThread
用於管理線程,而不是處理數據。 您應該改為QObject
子類。 閱讀此內容以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.