我完全坚持使用这个python qt线程教程。我有两个问题。
1)longRunning函数永远不会执行。 2)当退出应用程序时,我得到QThread:在线程仍在运行且Python.exe已停止工作时被销毁。
有任何帮助吗?谢谢!
#!/usr/bin/env python2
import sys, time
from PySide.QtGui import *
from PySide import QtCore
class SeperateThread(QtCore.QObject):
finished = QtCore.Signal()
def __init__(self, parent = None):
super(SeperateThread, self).__init__(parent)
self._isRunning = True
def longRunning(self):
end = time.time()+3
while self._isRunning == True:
sys.stdout.write('*')
sys.stdout.flush()
time.sleep(1)
now = time.time()
if now>=end:
self._isRunning=False
self.finished.emit()
def stop(self):
self._isRunning = False
class MainWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self,parent)
centralwidget = QWidget(self)
startButton = QPushButton('Start long (3 seconds) operation',self)
label2 = QLabel('Long batch')
vbox = QVBoxLayout()
vbox.addWidget(startButton)
vbox.addWidget(label2)
self.setCentralWidget(centralwidget)
centralwidget.setLayout(vbox)
obj = SeperateThread()
objThread = QtCore.QThread()
obj.moveToThread(objThread)
objThread.started.connect(obj.longRunning)
def LongOperationStart():
label2.setText('app is running')
startButton.setEnabled(False)
objThread.start()
def LongOperationFinish():
startButton.setEnabled(True)
#GUI start button
startButton.clicked.connect(LongOperationStart)
#Once thread is finished.
objThread.finished.connect(LongOperationFinish)
obj.finished.connect(objThread.quit)
if __name__=='__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:2)
哦,好吧,我发现我做错了什么:
MainWindow构造函数返回后,SeperateThread被垃圾收集。使obj成为MainWindow的成员,使其超出构造函数。
谢谢!