我无法从一个qthread向另一个qthread发送信号。我正在使用的类似代码摘录如下:
class auth(QtCore.QThread):
authenticate = pyqtSignal()
serverDown = pyqtSignal()
accntonline = pyqtSignal()
def __init__(self, parent=None):
super(auth, self).__init__(parent)
def run(self):
self.authenticate.emit()
class Threadclass(QtCore.QThread):
authenticator = "n"
def __init__(self, parent=None):
super(Threadclass, self).__init__(parent)
#setting first values avoiding errors
self.a = auth(self)
self.a.authenticate.connect(self.setauthentication)
#All small functions setting values from box.
def setauthentication(self):
print("awdawdawda")
self.authenticator = "y"
当我运行线程auth时,变量
self.authenticator
不会更改。它停留在“ n”。所有帮助表示赞赏
最佳答案
如果覆盖run
的QThread
方法,则除非您显式调用它的exec
方法,否则它将不会启动自己的事件循环。事件循环是处理跨线程信号所必需的。因此,通常最好创建一个工作器对象并将其移至线程,而不是覆盖run
。
这是一个演示脚本,显示了如何在线程中使用辅助对象:
import sys
from PyQt5 import QtWidgets, QtCore
class AuthWorker(QtCore.QObject):
authenticate = QtCore.pyqtSignal()
def __init__(self):
super(AuthWorker, self).__init__()
def run(self):
QtCore.QThread.sleep(0.5)
self.authenticate.emit()
class Worker(QtCore.QObject):
finished = QtCore.pyqtSignal(str)
authenticator = "n"
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
self.auth = AuthWorker()
self.auth_thread = QtCore.QThread()
self.auth.moveToThread(self.auth_thread)
self.auth.authenticate.connect(self.setauthentication)
self.auth_thread.started.connect(self.auth.run)
def setauthentication(self):
self.authenticator = "y"
def run(self):
self.auth_thread.start()
QtCore.QThread.sleep(1)
self.finished.emit('auth: %s' % self.authenticator)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtWidgets.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
self.edit = QtWidgets.QLineEdit(self)
self.edit.setReadOnly(True)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
self.thread = QtCore.QThread()
self.worker = Worker()
self.worker.moveToThread(self.thread)
self.worker.finished.connect(self.handleFinished)
self.thread.started.connect(self.worker.run)
def handleFinished(self, text):
self.thread.quit()
self.edit.setText(text)
def handleButton(self):
if not self.thread.isRunning():
self.edit.clear()
self.thread.start()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 200, 100)
window.show()
sys.exit(app.exec_())
关于python - Python在两个QThread之间发送信号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46531542/