线程时出现 msgbox 错误,GUI 块
问题描述
我在执行以下 gui 时遇到问题.如果没有消息框,它可以正常工作,但是当有消息框时,它会阻塞.知道为什么有消息时gui会阻塞.谢谢
I have a problem while executing the following gui. it works normally if there's no msgbox, but when there is a mesbox it blocks. any idea why the gui blocks when there is message. thank you
from PyQt5 import QtCore, QtGui, QtWidgets
import threading
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.pressed.connect(self.threadingc)
def calculation(self):
for i in range(10):
time.sleep(1)
print(i)
msg = QtWidgets.QMessageBox()
msg.setInformativeText('Finish')
msg.exec_()
def threadingc(self):
x=threading.Thread(target=self.calculation)
x.start()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
import sys
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
解决方案
任何访问 UI 元素只允许在主 Qt 线程内.请注意,access 不仅意味着读取/写入小部件属性,还意味着创建;任何从其他线程执行此操作的尝试在最好的情况下都会导致图形问题或不一致的行为,而在最坏(和更常见)的情况下会导致崩溃.
Any access to UI elements is only allowed from within the main Qt thread. Note that access means not only reading/writing widget properties, but also creation; any attempt to do so from other threads results in graphical issues or incosistent behavior in the best case, and a crash in the worst (and more common) case.
这样做的唯一正确方法是使用带有(可能)自定义信号的 QThread:这允许 Qt 正确地对信号进行排队,并在它可以实际处理它们时对它们做出反应.
The only correct way to do so is to use a QThread with (possibly) custom signals: this allows Qt to correctly queue signals and react to them when it can actually process them.
以下是一个非常简单的情况,不需要创建 QThread 子类,但请考虑这只是为了教育目的.
The following is a very simple situation that doesn't require creating a QThread subclass, but consider that this is just for educational purposes.
class Ui_MainWindow(object):
# ...
def calculation(self):
for i in range(10):
time.sleep(1)
print(i)
def showMessage(self):
msg = QtWidgets.QMessageBox()
msg.setInformativeText('Finish')
msg.exec_()
self.pushButton.setEnabled(True)
def threadingc(self):
self.pushButton.setEnabled(False)
self.thread = QtCore.QThread()
# override the `run` function with ours; this ensures that the function
# will be executed in the new thread
self.thread.run = self.calculation
self.thread.finished.connect(self.showMessage)
self.thread.start()
请考虑以下重要方面:
- 我必须禁用按钮,否则可以在前一个线程仍在执行时创建一个新线程;这会产生问题,因为覆盖
self.thread
会导致 python 在运行时尝试垃圾收集(删除)前一个线程,这是一个非常糟糕的 东西; - 一个可能的解决方案是使用父线程创建线程,这通常使用简单的
QThread(self)
来完成,但在您的情况下这是不可能的,因为 Qt 对象只能接受其他Qt 对象作为它们的父对象,而在您的情况下self
将是一个Ui_MainWindow
实例(这是一个基本的 python 对象); - 以上几点是一个重要问题,因为您尝试从
pyuic
生成的文件开始执行程序,而这永远不会这样做:这些文件是打算保持原样而无需任何手动修改,并且仅用作导入的模块;阅读有关 使用 Designer 的官方指南中有关此主题的更多信息;另请注意,试图模仿这些文件的行为是没有用的,因为这通常会导致对象结构非常混乱; - 理论上,您可以添加对 qt 对象的引用(例如,通过在
setupUi()
函数中添加self.mainWindow = MainWindow
)并使用该引用 (thread = QThread(self.mainWindow)
),或将线程添加到持久列表 (self.threads = []
,再次在setupUi()
),但由于上述原因,我强烈建议您不要这样做;
- I had to disable the pushbutton, otherwise it would be possible to create a new thread while the previous one still executing; this will create a problem, since overwriting
self.thread
will cause python to try to garbage collect (delete) the previous thread while running, which is a very bad thing; - a possible solution to this is to create the thread with a parent, which is usually done with a simple
QThread(self)
, but that's not possible in your case because Qt objects can accept only other Qt objects as their parent, while in your caseself
would be aUi_MainWindow
instance (which is a basic python object); - the above point is an important issue, because you're trying to implement your program starting from a
pyuic
generated file, which should never be done: those files are intended to be left as they are without any manual modification, and used only as imported modules; read more about this topic on the official guidelines about using Designer; also note that trying to mimic the behavior of those files is useless, as normally leads to great confusion about object structure; - you could theoretically add a reference to a qt object (for example, by adding
self.mainWindow = MainWindow
in thesetupUi()
function) and create the thread with that reference (thread = QThread(self.mainWindow)
), or add the thread to a persistent list (self.threads = []
, again in thesetupUi()
), but due to the above point I strongly discourage you to do so;
最后,更正确代码实现将要求您再次生成 ui 文件,保持原样并执行类似以下示例的操作;请注意,我添加了一个非常基本的异常实现,它还展示了如何正确地与自定义信号交互.
Finally, a more correct implementation of your code would require you to generate again the ui file, leave it as it is and do something like the following example; note that I added a very basic exception implementation that also shows how to correctly interact with custom signals.
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
import time
class Calculation(QtCore.QThread):
error = QtCore.pyqtSignal(object)
def run(self):
for i in range(10):
time.sleep(1)
print(i)
try:
10 / 0
except Exception as e:
self.error.emit(e)
break
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.pressed.connect(self.threadingc)
def showMessage(self):
msg = QtWidgets.QMessageBox()
msg.setInformativeText('Finish')
msg.exec_()
def threadingc(self):
# create the thread with the main window as a parent, this is possible
# since QMainWindow also inherits from QObject, and this also ensures
# that python will not delete it if you want to start another thread
thread = Calculation(self)
thread.finished.connect(self.showMessage)
thread.error.connect(self.showError)
thread.start()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在上述情况下,使用以下命令处理 ui 文件(显然,假设 ui 名为mainwindow.ui"):
In the above case, the ui file was processed using the following command (assuming that the ui is named "mainwindow.ui", obviously):
pyuic mainwindow.ui -o mainwindow.py
相关文章