gpt4 book ai didi

python - 如果将 QThread 创建为局部变量,为什么 QThread 的行为会有所不同

转载 作者:行者123 更新时间:2023-12-01 01:25:03 26 4
gpt4 key购买 nike

如果我创建 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() 方法将被执行,但在 main 中生成 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_())

关于python - 如果将 QThread 创建为局部变量,为什么 QThread 的行为会有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com