如果将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()
需要指出的问题是,它是一个局部变量,在启动
QThread
之后不久就会被销毁,因此由QThread
处理的线程(QThread不是线程,它是一个线程处理程序),当使用wait()
时,预期run()
方法将被执行,但在生成GUI的主线程中会被冻结。你知道吗因此,解决方案是延长变量线程的生命周期,一种方法是指出它是有效的:使其成为类的成员,但还有另一种方法只能将QObjects作为QThread使用,即传递一个父对象(父对象必须是另一个QObject),将对象的生命周期延长到与父对象相同的容量,例如所以我会用对话框。你知道吗
最后,现在不建议动态创建信号,最好将其作为类的一部分创建,对于必须使用the new syntax的连接也是如此。你知道吗
相关问题 更多 >
编程相关推荐