2014-09-23 154 views
0

我試圖通過將一些阻止代碼移動到單獨的QThread來使我的PyQt4程序更具響應性。由於沒有工作,我創造了這個小例子,作爲示範:pyqt代碼阻塞,雖然移動到不同的QThread

import sys 
import time 
from PyQt4 import QtCore, QtGui 


class Sleeper(QtCore.QObject): 

    def __init__(self): 
     super(Sleeper, self).__init__() 
     self.timer = QtCore.QTimer() 
     self.timer.timeout.connect(self.sleep) 
     self.timer.start(1000) 

    def sleep(self): 
     time.sleep(1) 


class MyGUI(QtGui.QMainWindow): 

    def __init__(self, parent=None): 
     super(MyGUI, self).__init__(parent) 
     self.button = QtGui.QPushButton("hello", self) 
     self.sleeper = Sleeper() 
     self.thread = QtCore.QThread() 
     self.sleeper.moveToThread(self.thread) 
     self.thread.start() 


if __name__ == "__main__": 
    qapp = QtGui.QApplication(sys.argv) 
    my_gui = MyGUI() 
    my_gui.show() 
    qapp.exec_() 

這段代碼的問題是睡眠命令仍然讓用戶界面。我發現它在我創建,連接並運行Sleeper類之外的QTimer時按預期工作,但我不明白爲什麼。

回答

3

當對象位於GUI線程中時調用connect,因此事件處理程序也將在GUI線程中執行。嘗試先移到線程,然後創建連接。

class Sleeper(QtCore.QObject): 

    def __init__(self): 
     super(Sleeper, self).__init__() 
     self.timer = QtCore.QTimer() 

    def initialize(self): # Creating the connection and starting separately 
     self.timer.timeout.connect(self.sleep) 
     self.timer.start(1000) 

    def sleep(self): 
     time.sleep(1) 

class MyGUI(QtGui.QMainWindow): 

    def __init__(self, parent=None): 
     super(MyGUI, self).__init__(parent) 
     self.button = QtGui.QPushButton("hello", self) 
     self.sleeper = Sleeper() 
     self.thread = QtCore.QThread() 
     self.sleeper.moveToThread(self.thread) # Move to thread 
     self.sleeper.initialize() # Create connection now 
     self.thread.start() 

此外,檢查: Qt connection type between threads: why does this work?

+0

我使用這段代碼仍然得到堵塞的UI。 – nvd 2014-10-28 22:35:37