qt inherited signal won't reach to slot
here's the code of my problem
class Base : QThread
{
Q_OB开发者_如何学CJECT
virtual void run() = 0;
signals:
void Ping(int);
};
class Derived : public Base
{
void run()
{
emit Ping(42);
}
}
the signal(42) won't reach/call to slots. what's wrong? thanks in advance.
Did that 100 times, it does work. Are you sure your base class is properly MOC'ed ? (i.e. defined in a file contained in HEADERS section of .pro
) Also when connecting your signal, check the return status of QObject::connect
(it's a boolean). A good practice is something like that
bool r=false;
r=QObject::connect(pObj1,SIGNAL(signalStuff()),pObj2,SLOT(gotStuff()));
Q_ASSERT(r);
As Liz noticed, if something went wrong in your connect
, you can check the traces to know what happened.
I can also note :
- you don't have to redefine
run
in your base class, it's already defined by QThread - Common pitfall with
QThread
: Base class and Derived class belong to the thread which created them, not in the newly created thread - you don't connect your signal to any slot in your sample, so it won't trigger anything (I suppose it's done elsewhere)
- your class Derived lacks the final
;
EDIT:
Edited to take into account liz' interesting comment.
I came upon the same problem but managed to find solution. The problem in my case wasnt the inheritance (even tho i did emit from derived class).
The problem was the code calling emit signal was execute BEFORE the code connecting signal with slot. Therefor both signal was emitted and signal-slot connection worked fine, but the code in the slot wasnt executed because emit happened before connecting the slot to signal.
Maybe that helps someone in the future.
I think you are trying to connect signal and slot from different threads. Did you read this article?
精彩评论