[Qt-interest] QThread and QTimer signal problems

Tony Rietwyk tony.rietwyk at rightsoft.com.au
Sat Feb 14 01:05:20 CET 2009


Donal wrote:

Hi,

I am doing serial communication and basically I want to set up a time out
facility.
Here would be the pseudocode code in main thread is:

myTimerThread->startTimer(300 msecs)
while (readCommport(charBuff) && !myTimerThread->hasTimedOut());
myTimerThread->stopTimer();

So I've created a timeout thread that creates a QTimer object in its
constructor with single shot.
I then connect the timeout signal to a slot I've created, "timedOut()". This
timedOut slot changes a bool attribute "hasTimedOut".
In the run method of my thread, I've placed it in an event loop using
QThread::exec();
I start the timer by calling a member method of my timer thread.
So in my while in the main thread I keep calling a function hasTimedOut()
that returns hasTimedOut variable.
The problem is, the timeout() signal from the QTimer never emits a signal.

I've placed qDebugs everywhere, including the hasTimedOut function and it
does get called but the bool attribute never gets changed as the slot is
never called by QTimer.

I've placed a delay in the readCommport function to force it to time out but
the QTimer never seems to emit the signal.

I came across an old post that claimed that you could only use QTimer in the
main thread, but looking at the docs, it says you can place it in any event
loop'd thread.

Am I doing something fundamentally wrong here? If not I'll post some code
later.

Thanks.

Donal
 

Hi Donal, 
 
This is a common problem with Qt threads - you have to create the objects
used by the thread in the run method - not in the thread's constructor. 
 
Do you see any debug warnings from Qt when the application runs? 
 
Also note that QTimer relies on the main event loop - so it cannot be used
for time critical operations (at least on Windows), since the timer (even in
a different thread) will not fire when the user drags the window around, or
resizes it. You need to use platform specific non-event timers in these
cases. 
 
Hope that helps, 
 
Tony.
 
 
 
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090214/7732d7e1/attachment.html 


More information about the Qt-interest-old mailing list