问题描述
我在执行以下 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 case self would be a ui_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 the setupui() function) and create the thread with that reference (thread = qthread(self.mainwindow)), or add the thread to a persistent list (self.threads = [], again in the setupui()), 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
我也不知道为什么