gpt4 book ai didi

python - PyQt4 : inheriting QThread

转载 作者:行者123 更新时间:2023-11-30 23:31:09 26 4
gpt4 key购买 nike

我有一个QWidget,它使用QThread调用一些python代码。然后,该代码还执行一些逻辑并调用另一个类。在此类中,我想将信号传递到我的 QWidget,以便打印“Hello World”。目前的代码给出了错误 sm instance has no attribute 'sayHello',我知道 - 我只是非常不知道如何使 run 方法调用不同的方法类以便所有信号正常工作。

widget.py

from prog import TaskThread
from PyQt4 import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self):
self.btn = QtGui.QPushButton('Run!', self)
self.btn.clicked.connect(self.onStart)
self.myLongTask = TaskThread()
self.myLongTask.sayHello.connect(self.sayHi)

def onStart(self):
self.myLongTask.start()

def sayHi(self):
print "hello world"

prog.py

from PyQt4 import QtCore 
from sm import sc
class TaskThread(QtCore.QThread):
sayHello = QtCore.pyqtSignal()
def run(self):
sm.sc()

sm.py

class sc():
def __init__(self):
for i in range(0,50):
print i
if i == 5: self.sayHello.emit()

最佳答案

我必须稍微改变你的代码才能让它在我的机器上运行,但是手动将信号实例传递给 sc 类肯定会引发信号。输出可能与 i 循环的打印交错。

widget.py

from prog import TaskThread
import sys
from PyQt4 import QtCore, QtGui

class flexemWidget(QtGui.QWidget):
def __init__(self):
super(flexemWidget, self).__init__()
self.btn = QtGui.QPushButton('Run!', self)
self.btn.clicked.connect(self.onStart)
self.myLongTask = TaskThread()
self.myLongTask.sayHello.connect(self.sayHi)
self.show()

def onStart(self):
self.myLongTask.start()

def sayHi(self):
print "hello world"

app = QtGui.QApplication(sys.argv)
ex = flexemWidget()
sys.exit(app.exec_())

prog.py

from PyQt4 import QtCore 
from sm import sc
class TaskThread(QtCore.QThread):
sayHello = QtCore.pyqtSignal()
def run(self):
sc(self.sayHello)

sc.py

from PyQt4 import QtCore
class sc():
def __init__(self, signal):
for i in range(0,50):
print i
if i == 5: signal.emit()

关于python - PyQt4 : inheriting QThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20148172/

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