Jeffrey04
Jeffrey04

Reputation: 6338

PySide: QTimer needs QApplication to work?

Just started learning PySide and is having problem with QTimer

I have this

#!/usr/bin/python

from PySide.QtCore import QThread;
from classes import Updater;

if __name__ == "__main__":
    thread = QThread();
    thread.start();

    update = Updater();
    update.moveToThread(thread);
    update.run();

and this

class Updater(QObject):
    def update_mode(self):
        #do something
        pass;

    def run(self):
        timer = QTimer();
        timer.timeout.connect(self.update_mode);
        timer.start(10);

I want my script to do some work periodically using QTimer (wanted to try QSystemAlignedTimer but that looks even more complicated to me for now...). Not sure what is wrong at the moment because I am getting this error

QObject::startTimer: QTimer can only be used with threads started with QThread
QEventLoop: Cannot be used without QApplication
QThread: Destroyed while thread is still running

Upvotes: 2

Views: 2474

Answers (1)

D K
D K

Reputation: 5760

QTimer, along with all other event based classes, need there to be a QApplication instance.

In:

thread = QThread();
thread.start();

update = Updater();
update.moveToThread(thread);
update.run();

First of all, get rid of the semicolons. Python programmers don't like those. If you take a close look at what your code is doing, you are making a QThread, starting it, making an Updater, moving it to the thread, running it, and ending the program. There is no command here telling Python to keep the program running, so it ends, and the QThread complains about being destroyed.

What you should do is make a QApplication, with something like

app = QApplication(sys.argv)

and the call app.exec_() to start it. In this case, this is essentially equivalent to time.sleep(9999999999...), but what it actually does is it processes events (signals/slots) endlessly. With time.sleep(9999999999...), QTimers will never do anything when they time out.

As a QApplication is an infinite loop, you will have to manually exit within your code.

Upvotes: 5

Related Questions