PyQt QThread:如何在同一线程中的辅助对象上运行函数?

时间:2019-05-14 08:19:28

标签: python pyqt pyqt5 qthread

我只是不知道如何正确使用QThreads。我有一个工作器对象,以及一个有两个组合框的gui:当用户在comboWorkspace上选择一个项目时,comboModel上的项目将加载。发生的事情是,每当我从comboWorkspace中选择时,它将再次从worker中运行get_workspaces函数。这可能是因为我一遍又一遍地调用QThread的“启动”功能。如果这里有很多错误,我感到很抱歉。如果有人可以给马一个想法,如何正确地解决这个问题。非常感谢!

*带有setupUi功能的完整代码在这里:pastebin.com/Y7dGbRLu

from PyQt5 import QtCore, QtGui, QtWidgets
import os
import time
from functools import partial
import copy

class anaplanWorker(QtCore.QObject):

    signal_workspacenames = QtCore.pyqtSignal(str)
    signal_modelnames = QtCore.pyqtSignal(str)
    finish_progressbar = QtCore.pyqtSignal()
    start_progressbar = QtCore.pyqtSignal()
    finish_workspace_thread = QtCore.pyqtSignal()
    finish_model_thread = QtCore.pyqtSignal()
    count_run = 0

    def __init__(self, parent=None):
         QtCore.QThread.__init__(self, parent)


    def get_workspaces(self):
        ws_names = ['Name One', 'Name Two', 'Name Three']

        self.start_progressbar.emit()
        for ws_name in ws_names:
            self.signal_workspacenames.emit(ws_name)

        self.finish_workspace_thread.emit()


    def get_models(self,workspaceindex):

        self.start_progressbar.emit()

        models = ['Model One', 'Model Two', 'Model Three']

        for model_name in models:
            self.signal_modelnames.emit(model_name)

        self.finish_model_thread.emit()


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        """ui setup for combo combo boxes: comboWorkspace and comboModel"""

    def progress_start(self):
        print("start")

    def progress_finish(self):
        print("finish")

#workspace functions
    def add_workspace(self, workspace_name):
        self.comboWorkspace.addItem(workspace_name)

    def start_workspace(self):

        self.comboWorkspace.clear()
        self.workspace_thread = self.anaplan_thread
        self.anaplan_worker.moveToThread(self.workspace_thread)
        self.workspace_thread.started.connect(self.anaplan_worker.get_workspaces)        
        self.workspace_thread.start()

#model functions
    def add_model(self, model_name):
        self.comboModel.addItem(model_name)

    def start_model(self):
        #clear combomodel
        self.comboModel.clear()
        workspaceIndex = self.comboWorkspace.currentIndex()

        self.model_thread = self.anaplan_thread
        self.anaplan_worker.moveToThread(self.model_thread)

        self.model_thread.started.connect(partial(self.anaplan_worker.get_models, workspaceIndex))

        self.model_thread.start()

#quit threads
    def quit_model_thread(self):
        self.model_thread.quit()
        print("quit model thread")

    def quit_workspace_thread(self):
        self.workspace_thread.quit()
        print("quit workspace thread")


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Tool"))
        self.labelWorkspace.setText(_translate("MainWindow", "Workspace"))
        self.labelModel.setText(_translate("MainWindow", "Model"))

        self.anaplan_worker = anaplanWorker()
        self.anaplan_thread = QtCore.QThread()

        self.anaplan_worker.signal_workspacenames.connect(self.add_workspace)

        self.anaplan_worker.signal_modelnames.connect(self.add_model)

        self.anaplan_worker.finish_workspace_thread.connect(self.quit_workspace_thread)

        self.anaplan_worker.finish_model_thread.connect(self.quit_model_thread)

        self.comboWorkspace.activated[str].connect(self.start_model)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.start_workspace()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

您应该进一步拆分代码。它将解决您的很多问题。

您有两个主要问题:每次更改索引时都要重新设置信号/插槽连接(一个连接表示一个呼叫)。您将同一线程用于两项不同的任务。

您应该创建一个新的类MainWindow并在其中移动业务逻辑。您的Ui_MainWindow类应仅处理UI部件(小部件,布局等)。

您的anaplanWorker有很多问题:它是QObject的继承人,但却调用QThread.__init__,您用它创建线程和对象 worker 。直接使用QThread会更清楚。

该类也应分为两个不同的部分:一个用于工作空间,另一个用于模型:

class ModelWorker(QtCore.QObject):

    signal_modelnames = QtCore.pyqtSignal(str)
    finish_progressbar = QtCore.pyqtSignal()
    start_progressbar = QtCore.pyqtSignal()
    finish_model_thread = QtCore.pyqtSignal()

    def __init__(self, parent=None):
         super().__init__(parent) 

    def get_models(self,workspaceindex):
        print("Get models with", workspaceindex)
        self.start_progressbar.emit()

        models = ['Model One', 'Model Two', 'Model Three']

        for model_name in models:
            self.signal_modelnames.emit(model_name)

        self.finish_model_thread.emit()

class WorkspaceWorker(QtCore.QObject):
    signal_workspacenames = QtCore.pyqtSignal(str)
    finish_progressbar = QtCore.pyqtSignal()
    start_progressbar = QtCore.pyqtSignal()
    finish_workspace_thread = QtCore.pyqtSignal()
    finish_model_thread = QtCore.pyqtSignal()

    def __init__(self, parent=None):
         super().__init__(parent)


    def get_workspaces(self):
        ws_names = ['Name One', 'Name Two', 'Name Three']

        self.start_progressbar.emit()
        for ws_name in ws_names:
            self.signal_workspacenames.emit(ws_name)

        self.finish_workspace_thread.emit()

然后,在MainWindow类中,创建并设置线程和连接。您只需要在需要时启动线程即可。

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setupUi(self)

        self.workspaceWorker = WorkspaceWorker()
        self.modelWorker = ModelWorker()

        self.workspaceWorker_thread = QThread(self)
        self.modelWorker_thread = QThread(self)

        self.workspaceWorker.moveToThread(self.workspaceWorker_thread)
        self.modelWorker.moveToThread(self.modelWorker_thread)

        self.workspaceWorker.signal_workspacenames.connect(self.add_workspace)
        self.workspaceWorker.finish_workspace_thread.connect(self.quit_workspace_thread)

        self.modelWorker.signal_modelnames.connect(self.add_model)
        self.modelWorker.finish_model_thread.connect(self.quit_model_thread)

        self.comboWorkspace.activated[str].connect(self.start_model)

        self.modelWorker_thread.started.connect(lambda: self.modelWorker.get_models(self.comboWorkspace.currentIndex()))
        self.workspaceWorker_thread.started.connect(self.workspaceWorker.get_workspaces)

        self.start_workspace()


    def add_workspace(self, workspace_name):
        self.comboWorkspace.addItem(workspace_name)

    def start_workspace(self):

        self.comboWorkspace.clear()
        self.workspaceWorker_thread.start()

#model functions
    def add_model(self, model_name):
        self.comboModel.addItem(model_name)

    def start_model(self):
        #clear combomodel
        self.comboModel.clear()
        self.modelWorker_thread.start()

#quit threads
    def quit_model_thread(self):
        self.modelWorker_thread.quit()
        print("quit model thread")

    def quit_workspace_thread(self):
        self.workspaceWorker_thread.quit()
        print("quit workspace thread")