简体   繁体   中英

Qt: Using signals and slots between two child threads

I'm new to Qt, and C++ in general, and I'm trying to make a program that runs two child threads, threadA and threadB. Both threads are created in main.cpp like so:

ThreadA threadA;
threadA.start();
ThreadB threadB;
threadB.start();

The two threads then run independently. I need to make threadA able to call a method in threadB, passing data as an argument in the process. I have tried using signals and slots, by adding this to my main.cpp:

QThread::connect(&threadA, SIGNAL(mySignal(uint)),
    &threadB, SLOT(mySlot(uint)));

Where threadA::mySignal(uint) is used in a:

//a.h
signals:
  void mySignal(unsigned int blah);
//a.cpp
  emit mySignal(42);

And threadB::mySlot(uint) is in b:

//b.h
public slots:
    void mySlot(unsigned int fluff);
//b.cpp
void threadB::mySlot(unsigned int fluff)
{ doStuff(fluff); ... }

The program compiles and runs sucessfully, but I get a message from QObject in my debug log:

QObject::connect: No such slot QThread::mySlot(uint) in ../Project/main.cpp:42

Meaning that the compiler is looking in QThread instead of threadB for mySlot. Can anyone tell me where I'm going wrong here? Any help would be gratly appreciated, and I can provide more details if nessesary.

First of all for the error you mentioned

The program compiles and runs sucessfully, but I get a message from QObject in my debug log:

QObject::connect: No such slot QThread::mySlot(uint) in ../Project/main.cpp:42

You are using mySlot and have defined MySlot please refer back your code

You have written

QThread::connect(&threadA, SIGNAL(mySignal(uint)), &threadB, SLOT( mySlot (uint)));

and defined

//bh

public slots:
    void MySlot(unsigned int fluff);

You are probably missing the Q_OBJECT macro in your threadb.h (and possibly threada.h ).

class ThreadB : public QObject 
{
   Q_OBJECT 
...

From the docs: 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.

I'm also assuming that you have subclassed QThread . You should know that QThread is used for managing threads, not processing data. You should subclass QObject instead. Read this for more info about that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM