[PyQt] how to set up a timer to call a method after a delay?

Phil Thompson phil at riverbankcomputing.com
Thu Jul 1 09:09:11 BST 2010


On Wed, 30 Jun 2010 17:53:38 -0700, Steve Castellotti <sc at puzzlebox.info>
wrote:
> On Wed, 2010-06-30 at 18:19 +0100, Phil Thompson wrote: 
>> > self.timer = QtCore.QTimer()
>> > self.timer.connect(self.timer, QtCore.SIGNAL("timeout()"),
>> > self.sendData)
>> > self.timer.start(1000) # 1 second
>> > 
>> >     ...but received an exception that "QTimer can only be used with
>> > threads started with QThread" which leads me to believe I will need to
>> > implement threading for my server (also I expected to need to send
>> > "parent=self" when instantiating the QTimer object so I know I must be
>> > doing something wrong).
>> 
>> QTimer.singleShot(1000, self.sendData)
>> 
>> ...is the normal way of doing it.
> 
>     Yes and thank you, that gets me closer to the style I was using
> under Twisted, however, with my code looking like this:
> 
> self.timer = QtCore.QTimer.singleShot(1000, self.sendData)

singleShot() is a static method - it doesn't return a value.

>     I'm still getting this error:
> 
> QObject::startTimer: QTimer can only be used with threads started with
> QThread

I think that is a misleading message - you need to provide a test case.

>     Comparing to an example I found online here:
> 
> http://www.rkblog.rk.edu.pl/w/p/qtimer-making-timers-pyqt4/

...which makes the same mistake regarding singleShot() - the "stimer"
QTimer is unused (but it won't make a difference).

>     The main difference that I can see is that example is using
> QApplication to start up, whereas I am only running from the console (no
> Gui at this point).
> 
> That said, QApplication inherits from QCoreApplication, which inherits
> from QObject. QThread also inherits form QObject, but there's nothing
> obvious I see that would indicate QApplication inherits from QThread
> directly. Is there some other component related to Gui applications
> which are creating QThreads which I need to replicated?

I don't think this will have anything to do with the problem.

> I tried setting up my program to inherit from QtCore.QThread just to see
> if that would cover it, but no joy.
> 
> Do I need to re-code my program to open each connection as distinct
> objects in dedicated threads and perform the timers within those
> objects, or again is there something simple and obvious which I am just
> missing?

Because Qt sockets are handled with the event loop you usually do not need
to use threads to handle multiple connections.

Phil


More information about the PyQt mailing list