在app.exec()返回后关闭PyQT应用程序时出错

时间:2017-12-20 23:49:17

标签: python pyqt pyqt5

每次从QT按钮退出一个简单的PyQT GUI时,我都会看到一个错误:Must construct a QGuiApplication first.在运行应用程序任何时间后出现错误,但只有在单击按钮时才会触发{{1} 1}}。如果通过关闭窗口停止应用程序,则没有错误。到目前为止,我只使用Ubuntu的PyQT软件包测试了Ubuntu Artful。

证明这一点的最简单的应用是:

test.py

Qt.quit()

test.qml

#!/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')

输出

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()返回之前。

干净地关闭PyQT还需要做些什么吗?

1 个答案:

答案 0 :(得分:1)

为了将大多数功能保留在#!/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) 中,最好的解决方案是将QGuiApplication()移到所有功能之外:

app.exec()

这很干净,但我仍然想知道如何完全关闭PyQT。我认为问题是事件循环中仍有事件试图在import timeit t = timeit.Timer(stmt="for num in num_list: print(num)", setup="num_list = [digit for digit in range(1, 101)]") print(t.timeit()) 返回后运行,但我还没有找到如何让它们运行完成并停止。

谢谢eyllanesc的帮助。