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

Phil Thompson phil at riverbankcomputing.com
Wed Jun 30 18:19:58 BST 2010


On Wed, 30 Jun 2010 04:46:36 -0700, Steve Castellotti <sc at puzzlebox.info>
wrote:
> Hello all-
> 
>     I have written a simple socket server based around
> QtNetwork.QTcpServer which I want to use to send a single stream of
> information to multiple connected clients, with updates pushed at a
> specific frequency (lets say once per second).
> 
>     I am a little confused how to set up a timer which will emit a
> signal that is connected to my method for sending the data.
> 
> 
>     For example, under Python Twisted, I might have something like this:
> 
> def sendData(self, timer):
>     data = self.getCurrentData()
>     self.sendLine(data)
>     reactor.callLater(timer, self.sendData, timer)
> 
>     ...whereby the "callLater" function makes sure the function happens
> at a regular interval.
> 
> 
>     I have tried setting up a QTimer object in the __init__ method of my
> socket server's class:
> 
> 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).
> 
> 
>     Is there an easier way to accomplish what I am trying to do?
> 
> 
>     If there is obvious documentation which I have overlooked please
> just point me in the right direction.

QTimer.singleShot(1000, self.sendData)

...is the normal way of doing it.

Phil


More information about the PyQt mailing list