Signal before starting the QThread loop

I have a case where a signal gets lost and I don't understand why - usually signals sent before the event loop are only fired in the queue and sent then.

This is what the code looks like (for a QThread object):

void OffloadHandler::run()
{
    cout << "Start" << endl;
    connect( this, SIGNAL(loopStarted()), SLOT(onLoopStarted()), Qt::QueuedConnection );
    emit loopStarted();
    exec();
}

void OffloadHandler::onLoopStarted()
{
    cout << "Here!" << endl;
}

      

The thread starts elsewhere and Start

writes to the console but Here1

never appears - no signal received. I use the same pattern in my main message loop and it works, but it doesn't work in this message flow loop.

Is there something clearly wrong in the code?

+1


source to share


2 answers


Your code is valid and should work. Are you sure oh

there is an event loop in the thread that is created ?

The reason is emit loopStarted()

to dispatch the event to the loop oh

to be handled and onLoopStarted()

called. I have checked your code and it works for me.




Btw, it is generally recommended that you do not add slots to yours QThread

and usemoveToThread( this );

Unfortunately I don't really understand your use case, so I can't give a better solution. But here is awesome documentation that has good DOs and DONTs regarding QThread

s.

+1


source


Ok I figured it out, I was bitten by the weirdness of QThread. You need to be very careful when connecting to the QThread object itself, as this object is not owned by the thread by default.

So, at the point where the thread is created, I have to move the thread to the thread:



OffloadHandler * oh = new OffloadHandler();
oh->moveToThread( oh ); //MOVE TO SELF!
oh->start();

      

Once I do this, the signals work as expected.

0


source







All Articles