【问题标题】:Error closing PyQT app, after app.exec() returns在 app.exec() 返回后关闭 PyQT 应用程序时出错
【发布时间】: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_())

标签: python pyqt pyqt5


【解决方案1】:

为了将大部分功能保留在main() 中,最好的解决方案是将 QGuiApplication() 移到所有函数之外:

#!/usr/bin/env python3

import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import PyQt5.QtQml as QtQml



def main(app):
    ''' setup and run the application '''

    # Create a QML engine.
    engine = QtQml.QQmlApplicationEngine(parent=app)

    engine.load(QtCore.QUrl('test.qml'))

    app.exec()

    return

if __name__ == '__main__':
    # Create the application instance.
    app = QtGui.QGuiApplication(sys.argv)

    main(app)

这完全退出,但我仍然想知道如何完全关闭 PyQT。我认为问题在于,在app.exec() 返回后,事件循环中仍有事件试图运行,但我还没有找到如何让它们运行完成并停止。

感谢 eyllanesc 的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多