【发布时间】:2017-12-20 23:49:16
【问题描述】:
每次从 QT Button 退出简单的 PyQT GUI 时,我都会看到一个错误:Must construct a QGuiApplication first. 该错误在运行应用程序任意时间后出现,但仅当单击触发 Qt.quit() 的按钮时才会出现此错误。如果应用程序通过关闭窗口停止,则没有错误。到目前为止,我只使用 Ubuntu 的 PyQT 包在 Ubuntu Artful 上进行了测试。
证明这一点的最简单的应用是:
test.py
>#!/usr/bin/env python3
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import PyQt5.QtQml as QtQml
def main():
''' setup and run the application '''
# Create the application instance.
app = QtGui.QGuiApplication([])
# Create a QML engine.
engine = QtQml.QQmlApplicationEngine(parent=app)
engine.load(QtCore.QUrl('test.qml'))
app.exec()
print('a') # <--- This is printed before the QT error message
return
if __name__ == '__main__':
main()
print('b')
test.qml
import QtQuick 2
import QtQuick.Controls 1.4
ApplicationWindow {
id: main_window
visible: true
Button {
text: "Quit"
onClicked: Qt.quit()
}
}
输出
a
Must construct a QGuiApplication first.
b
错误出现在app.exec() 完成之后,但在main() 返回之前。
是否需要执行其他操作才能彻底关闭 PyQT?
【问题讨论】:
-
一种解决方案是将应用程序定义为全局变量:
app = Nonedef main():global appapp = QtGui.QGuiApplication([]) -
谢谢,@eyllanesc 消除了错误。这是一种尴尬的方式。我关闭 QT 的方式有什么遗漏吗?
-
发生的情况是应用程序是一个局部变量,python需要删除它,但在你的情况下,作为一个本地应用程序,它已经被删除了。 main部分我直接放在
if __name__ == '__main __':,我的意思是:if __name__ == '__main__': import sys app = QtGui.QGuiApplication([]) engine = QtQml.QQmlApplicationEngine() engine.load(QtCore.QUrl('test.qml')) sys.exit(app.exec_())