如果将QThread创建为local variab,为什么它的行为不同

2024-04-26 20:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如果将QThread创建为局部变量,我发现了一个奇怪的行为。你知道吗

例如,下面的代码将作为单线程工作,这意味着我需要等待10秒,结果就会出来。你知道吗

但如果我把线程从局部变量改为成员变量,它就可以像多线程一样工作。你知道吗

怎么样了?谁能给我一些小费吗?你知道吗

class UI():
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.dialog = QtGui.QDialog()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self.dialog)
        self.ui.btn.clicked.connect(self.btnclick)

    def run(self):
        self.dialog.show()
        sys.exit(self.app.exec_())

    def btnclick(self):
        ## if change to self.thread, the behavior changes!!
        signal = QtCore.SIGNAL("Log(QString)")
        thread = testThread(signal)  
        QtCore.QObject.connect(thread, signal, self.output)
        thread.start()

    def output(self, txt):
        self.ui.logText.append(str(txt))

class testThread(QThread):
    def __init__(self, signal):
        QThread.__init__(self)
        self.signal = signal

    def __del__(self):
        self.wait()

    def run(self):
        for i in range(10):
            time.sleep(1)
            self.output(str(i))

    def output(self, txt):
        self.emit(self.signal, txt)


if __name__ == "__main__":
    ui = UI()
    ui.run()

Tags: runselftxtappuioutputsignalinit
1条回答
网友
1楼 · 发布于 2024-04-26 20:59:27

需要指出的问题是,它是一个局部变量,在启动QThread之后不久就会被销毁,因此由QThread处理的线程(QThread不是线程,它是一个线程处理程序),当使用wait()时,预期run()方法将被执行,但在生成GUI的主线程中会被冻结。你知道吗

因此,解决方案是延长变量线程的生命周期,一种方法是指出它是有效的:使其成为类的成员,但还有另一种方法只能将QObjects作为QThread使用,即传递一个父对象(父对象必须是另一个QObject),将对象的生命周期延长到与父对象相同的容量,例如所以我会用对话框。你知道吗

最后,现在不建议动态创建信号,最好将其作为类的一部分创建,对于必须使用the new syntax的连接也是如此。你知道吗

class UI():
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.dialog = QtGui.QDialog()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self.dialog)
        self.ui.btn.clicked.connect(self.btnclick)
        self.dialog.show()

    def btnclick(self):
        thread = testThread(self.dialog)  
        thread.signal.connect(self.output)
        thread.start()

    def output(self, txt):
        self.ui.logText.append(str(txt))

class testThread(QtCore.QThread):
    signal = QtCore.pyqtSignal(str)

    def __del__(self):
        self.wait()

    def run(self):
        for i in range(10):
            QtCore.QThread.sleep(1)
            self.output(str(i))

    def output(self, txt):
        self.signal.emit(txt)

if __name__ == '__main__':
    ui = UI()
    app = QtGui.QApplication.instance()
    if app is not None:
        sys.exit(app.exec_())

相关问题 更多 >