簡體   English   中英

Qt中的QThread在Python上

[英]QThread in Qt on Python

我使用的QThread使用閱讀的QThread應如何使用擴展的討論和通過繼承是不正確的方法重寫它的run方法后,一個工人對象。 但是,在我打算使用的方法中,我需要傳遞一個額外的函數參數,該參數在啟動線程時不可用,並且使用moveToThread將worker推送到線程。 按下按鈕時可以使用此信息(參數),並傳達有關要移動的對象的信息。

在我的代碼的完整版本中,有三個獨立的控制器用於三個獨立的對象,您可以在下面找到一個最小的工作示例,演示我嘗試傳遞參數的內容。 代碼也可以在pastebin上獲得,感興趣的行號是10-28,46-50和133-135。

到目前為止,我已嘗試在連接到worker中的實際函數的行中使用lambda構造函數。 那就是self.thread.started.connect(self.obj.moveLeftIncrement)這一行然后嘗試使用插槽 ,但我對它們並不了解。 此外,盡管使用QThread有時GUI掛起並且程序退出后出現錯誤,其中一個如下:

進程以退出代碼-1073740791(0xC0000409)結束

我的問題如下:

  1. 如何在運行時傳遞參數和/或使用插槽?
  2. 如何在退出時阻止程序錯誤?
  3. 為什么子類化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_())

- 如何在運行時傳遞參數和/或使用插槽?

如果要調用另一個線程中的對象的插槽,則必須使用信號,因為它是線程安全的。

- 如何在退出時防止程序錯誤?

在您的情況下,錯誤是由於您有一個線程正在運行並且您沒有停止它,可能的選擇是使用closeEvent來停止它。

- 為什么子類化QThread直接適用於這種情況,盡管不建議這樣做?

並不是不推薦它,但它非常有限,有更好的選擇,比如使用一個生活在另一個線程中的worker,所以我們可以有不同的方法而不只是在run方法中執行任務。 此外,通過工作人員的選項,您可以在線程中生成多個對象。


就工人而言,方法如下:

  • 創建一個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_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM