首页 > 解决方案 > Python PyQt5:根据条件,运行 CPU 密集型 QThread

问题描述

我正在尝试使用 PyQt5 在单独的 QThread 中运行 CPU 密集型任务。我已经尝试了代码的几种排列,只是得到了两个不需要的结果之一。

此错误:“QThread:在线程仍在运行时被销毁”

或者 GUI 挂起,就好像单独的线程不存在一样!

我创建了一个基本示例。我如何让它像我期望的那样工作?

最重要的是,我想根据条件是否为真来运行 QThread。如果为 True,则显示允许用户取消操作的警告。如果为 False,则只运行线程。

这是代码:

from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout, QMessageBox
from PyQt5.QtCore import QThread, QObject

class createMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setFixedSize(300, 100)
        self.setWindowTitle('Thread testing')
        self.show()


class createMainWidget(QWidget):
    def __init__(self):
        super().__init__()

        threadButton = QPushButton('Start thread!')
        threadButton.clicked.connect(self.startThread)

        layout = QVBoxLayout(self)
        layout.addWidget(threadButton)


    def startThread(self):
        thread = QThread()
        worker = createWorker()
        worker.moveToThread(thread)
        thread.started.connect(worker.run) # It's like this is invisible. It should work.

        # I want to display a warning message if a certain condition is met. If the warning is displayed, the user has the option of not continuing.
        displayMessage = True
        if displayMessage == True:
            warningMessage = QMessageBox()
            warningMessage.setIcon(QMessageBox.Warning)
            warningMessage.setWindowTitle('Warning')
            warningMessage.setText('Be warned!')
            warningMessage.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            warningMessage.accepted.connect(thread.start) # Why does this destroy the QThread straight away???
            warningMessage.exec_()

        # The condition is false, therefore just start the thread.
        elif displayMessage == False:
            thread.start() # This destroys the QThread as well. Why?



class createWorker(QObject):
    def __init__(self):
        super().__init__()

    def run(self):
        print('Secondary thread working')
        i = 0
        while i < 1000000000: i += 1 # Simulate CPU intensive activity
        print('Done')


app = QApplication([])

mainWidget = createMainWidget()
mainWindow = createMainWindow()
mainWindow.setCentralWidget(mainWidget)

app.exec_()


标签: python-3.xpyqt5qthread

解决方案


推荐阅读