Hello World / plɹoM ollǝH

Programmers Live in Vain

QTimer.singleShotをサブスレッドで使うには

呼び出しスレッド側でexec関数をよんでイベントループを開始せよ

QTimer Class | Qt 4.8

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

イベントループにはいるとexitを呼ぶまで帰ってこないので注意

from PySide import QtCore, QtGui
import sys, time

class SingleShotThread(QtCore.QThread):
    def run(self):
        QtCore.QTimer.singleShot(1000, lambda: print('hoge'))
        self.exec_()  # イベントループ開始

app = QtGui.QApplication(sys.argv)
th = SingleShotThread()
th.finished.connect(lambda: print('finished'))
th.start()
time.sleep(3)
th.exit()  # exitを呼んで終了させる
sys.exit(app.exec_())