如何从QML关闭Pyqt5程序?

时间:2015-06-02 03:48:52

标签: qt python-3.x qml signals-slots pyqt5

我最初使用C ++后端在Qt Creator中启动了一个项目,但后来将其切换为使用PyQt5。我有一个main.qml,当我按下一个名为Exit的按钮时,我会调用Qt.quit()

但是,我得到General Message陈述:Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.

我的问题是,我如何收到此信号并处理它?<​​/ p>

代码:

main.py:

import sys
import PyQt5

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtQml
from PyQt5.QtCore import QObject pyqtSignal


class DestinyManager,(QtGui.QGuiApplication):
    """the app self"""
    def __init__(self, argv):
        super(DestinyManager, self).__init__(argv)

    # Define a new signal called 'trigger' that has no arguments.
    trigger = pyqtSignal()

    def connect_and_emit_trigger(self):
        # Connect the trigger signal to a slot.
        self.trigger.connect(self.handle_trigger)
        self.menuItem_Exit.clicked.connect(self.close)
        # Emit the signal.
        self.trigger.emit()

    def handle_trigger(self):
        # Show that the slot has been called.
        print("trigger signal received")

def main(argv):
    app = DestinyManager(sys.argv)
    engine = QtQml.QQmlEngine(app)
    component = QtQml.QQmlComponent(engine)
    component.loadUrl(QtCore.QUrl("exit.qml"))
    topLevel = component.create()
    if topLevel is not None:
        topLevel.show()
    else:
        for err in component.errors():
            print(err.toString())
    app.exec()

if __name__ == '__main__':
    QObject,main(sys.argv)

Exit.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

Window {

    Button {
    id: btn_Exit
    text: "Exit"

    onClicked: Qt.quit();

    }
}

1 个答案:

答案 0 :(得分:1)

python脚本中有一些语法错误,但忽略了这些错误,代码可以像这样工作:

quit

也就是说,您只需要将qml {{1}}信号连接到python脚本中的相应插槽。