簡體   English   中英

無法使qthread示例正常工作

[英]Cannot get qthread example to work

我完全被這個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_())

哦,好的,我發現我做錯了什么:

在MainWindow構造函數返回后,將對SeperateThread進行垃圾回收。 使obj成為MainWindow的成員,這樣它就可以在構造函數之外繼續存在。

謝謝!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM