python-3.x - 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_()
解决方案
推荐阅读
- java - AlarmManager 的“setExact”方法行为不正确
- .net - 如何用公钥解密数据
- python - 使用 Python 使用下拉菜单 + 按钮进行抓取
- reactjs - 导入 redux action 使得其他 action 未定义
- xamarin.forms - 无法在 Xamarin 中使用 XML 文件填充对象
- python-3.x - 用于python`if`语句的Atom Hydrogen错误“解析时出现意外的EOF”!?(但不是其他陈述)
- node.js - 使用 multer 将图像上传到 Firebase 存储问题
- c++ - Cmake:制作静态库并在其他项目中使用
- excel - 在按钮单击期间将对象作为参数传递
- c++ - 我如何对给定大小的数组进行洗牌并将其与 C++ 中另一个相同大小的数组进行比较