Qt on Python 中的 QThread
Posted
技术标签:
【中文标题】Qt on Python 中的 QThread【英文标题】:QThread in Qt on Python 【发布时间】:2019-06-20 23:36:07 【问题描述】:在阅读了关于如何使用 QThread 的扩展讨论后,我使用 QThread 使用工作对象,并通过子类化覆盖它的 run 方法不是正确的方法。但是,在我打算使用的方法中,我需要传递一个额外的函数参数,该参数在启动线程并使用moveToThread
将工作线程推送到线程时不可用。此信息(参数)在按下按钮时可用,并传达有关要移动的对象的信息。
在我的代码的完整版本中,三个独立的控制器分别用于三个独立的对象,您可以在下面找到一个最小的工作示例,演示我试图传递参数的内容。该代码也可在pastebin 上获得,感兴趣的行号是 10-28、46-50 和 133-135。
到目前为止,我已经尝试在连接到 worker 中的实际函数的行中使用 lambda 构造函数。那是self.thread.started.connect(self.obj.moveLeftIncrement)
的行,然后尝试使用slots,但我不太了解它们。此外,尽管使用 QThread,有时 GUI 会挂起,并且程序退出后会出现错误,其中之一如下:
进程以退出代码 -1073740791 (0xC0000409) 结束
我的问题如下:
-
如何在运行时传递参数和/或使用槽?
如何防止退出时出现程序错误?
为什么在这种情况下子类化 QThread 直接起作用,虽然不推荐?
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from PySide2.QtGui import *
import sys
import time
class Worker(QObject):
finished = Signal(int)
@Slot(str)
def moveLeftIncrement(self, controller_name):
# controller_name = "Controller 1"
print("Controller name is ", controller_name)
if controller_name == "Controller 1":
print("Starting controller 1")
time.sleep(2)
print("Finishing sleep")
elif controller_name == "Controller 2":
print("Starting controller 2")
time.sleep(2)
print("Finishing sleep")
elif controller_name == "Controller 3":
print("Starting controller 3")
time.sleep(2)
print("Finishing sleep")
else:
raise Exception("No such controller found!")
self.finished.emit(0)
class Window(QWidget):
""" Inherits from QWidget """
def closeEvent(self, *args, **kwargs):
print("\nClosing")
def __init__(self):
super().__init__()
self.CONTINUOUS_MOVE_SWITCH = False
self.title = 'Control Controllers'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.AxesMapping = [0, 1, 2, 3]
self.initUI()
self.thread = QThread()
self.obj = Worker()
self.obj.moveToThread(self.thread)
self.thread.started.connect(self.obj.moveLeftIncrement)
self.obj.finished.connect(self.thread.quit)
def initUI(self):
""" Initializes the GUI either using the grid layout or the absolute position layout"""
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
Comp1 = self.createGridLayout("Controller 2")
windowLayout = QGridLayout()
windowLayout.addWidget(Comp1, 0, 0)
self.setLayout(windowLayout)
self.show()
def createGridLayout(self, controller):
"""Creates a grid layout for the buttons"""
box_size = QSize(640, 440)
HGroupBox = QGroupBox(controller)
layout = QGridLayout()
layout.addWidget(self.createButton("left", controller), 2, 1)
layout.addWidget(self.createButton("right", controller), 2, 3)
layout.addWidget(self.createButton("forward", controller), 1, 2)
layout.addWidget(self.createButton("backward", controller), 3, 2)
HGroupBox.setLayout(layout)
HGroupBox.setFixedSize(box_size)
return HGroupBox
def createButton(self, name, controller):
"""Creates a button with the specified size"""
button_size = QSize(100, 40)
icon_size = 40
button = QPushButton()
button.Name = name
button.Controller = controller
button.Moving = 0
button.clicked.connect(lambda: self.buttonPresssed(button))
button.setFixedSize(button_size)
return button
def moveLeftIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
raise Exception("No such controller found!")
def moveRightIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
raise Exception("No such controller found!")
def moveForwardIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
raise Exception("No such controller found!")
def moveBackwardIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
raise Exception("No such controller found!")
def buttonPresssed(self, button):
name = button.Name
if hasattr(button, 'Controller'):
controller = button.Controller
print("The controller selected is", controller)
if name == 'left':
self.thread.start()
elif name == 'right':
print("Moved controller right for a single step")
self.moveRightIncrement(controller, button)
elif name == 'forward':
self.moveForwardIncrement(controller, button)
print("Moved controller forward for a single step")
elif name == 'backward':
self.moveBackwardIncrement(controller, button)
print("Moved controller backward for a single step")
elif name == "up":
print("Moving controller up for a single step")
self.moveUpIncrement(controller, button)
elif name == "down":
print("Moving controller down for a single step")
self.moveDownIncrement(controller, button)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Window()
sys.exit(app.exec_())
【问题讨论】:
【参考方案1】:- 如何在运行时传递参数和/或使用槽?
如果你想调用另一个线程中的对象的槽,你必须使用信号,因为它是线程安全的。
- 如何防止退出时出现程序错误?
在你的情况下,错误是因为你有一个线程正在运行而你没有停止它,一个可能的选择是使用 closeEvent 来停止它。
- 为什么不推荐子类化 QThread 在这种情况下直接起作用?
不是不推荐,而是非常有限,有更好的选择,比如使用一个存在于另一个线程中的工作线程,这样我们就可以有不同的方法,而不仅仅是在 run 方法中执行任务。还可以通过 worker 选项让多个对象存在于一个线程中。
在工人的情况下,方法如下:
创建一个 QThread 并启动处理的线程。 创建一个将存在于另一个线程中并移动另一个线程的对象 连接调用对象槽的信号,也连接将发送对象信息到 GUI 的信号。 发出他们将在必要时调用的信号。综合以上,解决办法是:
from PySide2 import QtCore, QtGui, QtWidgets
import time
class Worker(QtCore.QObject):
error = QtCore.Signal()
@QtCore.Slot(str)
def moveLeftIncrement(self, controller):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
self.error.emit("No such controller found!")
@QtCore.Slot(str)
def moveRightIncrement(self, controller):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
self.error.emit("No such controller found!")
@QtCore.Slot(str)
def moveForwardIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
self.error.emit("No such controller found!")
@QtCore.Slot(str)
def moveBackwardIncrement(self, controller, button):
if controller == "Controller 1":
time.sleep(2)
elif controller == "Controller 2":
time.sleep(2)
elif controller == "Controller 3":
time.sleep(2)
else:
self.error.emit("No such controller found!")
class Window(QtWidgets.QWidget):
leftClicked = QtCore.Signal(str)
rightClicked = QtCore.Signal(str)
forwardClicked = QtCore.Signal(str)
backwardClicked = QtCore.Signal(str)
def __init__(self):
super().__init__()
self.CONTINUOUS_MOVE_SWITCH = False
self.title = 'Control Controllers'
self.left, self.top, self.width, self.height = 10, 10, 320, 100
self.AxesMapping = [0, 1, 2, 3]
self.initUI()
self.thread = QtCore.QThread(self)
self.thread.start()
self.obj = Worker()
self.obj.moveToThread(self.thread)
self.leftClicked.connect(self.obj.moveLeftIncrement)
self.rightClicked.connect(self.obj.moveRightIncrement)
self.forwardClicked.connect(self.obj.moveForwardIncrement)
self.backwardClicked.connect(self.obj.moveBackwardIncrement)
self.obj.error.connect(self.on_error)
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
Comp1 = self.createGridLayout("Controller 2")
windowLayout = QtWidgets.QGridLayout(self)
windowLayout.addWidget(Comp1, 0, 0)
def createGridLayout(self, controller):
"""Creates a grid layout for the buttons"""
box_size = QtCore.QSize(640, 440)
HGroupBox = QtWidgets.QGroupBox(controller)
layout = QtWidgets.QGridLayout()
layout.addWidget(self.createButton("left", controller), 2, 1)
layout.addWidget(self.createButton("right", controller), 2, 3)
layout.addWidget(self.createButton("forward", controller), 1, 2)
layout.addWidget(self.createButton("backward", controller), 3, 2)
HGroupBox.setLayout(layout)
HGroupBox.setFixedSize(box_size)
return HGroupBox
def createButton(self, name, controller):
button_size = QtCore.QSize(100, 40)
icon_size = 40
button = QtWidgets.QPushButton()
button.Name = name
button.Controller = controller
button.Moving = 0
button.clicked.connect(self.buttonPresssed)
button.setFixedSize(button_size)
return button
@QtCore.Slot()
def buttonPresssed(self):
button = self.sender()
name = button.Name
if hasattr(button, 'Controller'):
controller = button.Controller
print("The controller selected is", controller)
if name == 'left':
self.leftClicked.emit(controller)
elif name == 'right':
print("Moved controller right for a single step")
self.rightClicked.emit(controller)
elif name == 'forward':
print("Moved controller forward for a single step")
self.forwardClicked.emit(controller)
elif name == 'backward':
print("Moved controller backward for a single step")
self.backwardClicked.emit(controller)
@QtCore.Slot(str)
def on_error(self, error):
print(error)
def closeEvent(self, event):
self.thread.quit()
self.thread.wait()
super(Window, self).closeEvent(event)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
【讨论】:
感谢您的及时和简洁的回复。我对 Qt 中的信号/插槽感到非常困惑。我今天将在完整的代码中尝试它。顺便说一句,是否可以在QtCore.Slot
中使用自定义类?假设我有一个名为 Controller 的类,我可以执行以下操作吗? @QtCore.Slot(Controller) def moveForwardIncrement(self, Controller): controller = Controller.name if controller == "Controller 1": time.sleep(2) elif controller == "Controller 2": time.sleep(2) self.error.emit("没有找到这样的控制器!")以上是关于Qt on Python 中的 QThread的主要内容,如果未能解决你的问题,请参考以下文章
PyQt5遇到的一个坑 "ImportError: unable to find Qt5Core.dll on PATH" 及解决办法