QML出现Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.

两个文件的代码如下,实现的功能很简单:点击Rectangle窗口中的Quit按钮,窗口关闭

//main.cpp
#include <QGuiApplication>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView viewer;
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setSource(QUrl("qrc:///main.qml"));
    viewer.show();

    return app.exec();
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.14

//Button的clicked事件响应onClicked

Rectangle {
    width: 640; 
     height: 480;
    color: "gray";

    Button {
        text: "Quit";
        anchors.centerIn: parent;
        onClicked: {
            Qt.quit();
        }
    }
}

运行提示:Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.

解决方法:如果使用的是Rectangle,在main.cpp中include QQmlEngine库,再加上

QObject::connect(viewer.engine(), SIGNAL(quit()), &app, SLOT(quit()));即可。&app也可以用qApp替代。qApp是一个宏。

官方帮助文档
This function causes the QQmlEngine::quit() signal to be emitted. Within the Prototyping with qmlscene, this causes the launcher application to exit; to quit a C++ application when this method is called, connect the QQmlEngine::quit() signal to the QCoreApplication::quit() slot.

//main.cpp
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlEngine>
#include <QObject>//<----------------------------------------------------------------新添加的——需要包含头文件

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView viewer;
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setSource(QUrl("qrc:///main.qml"));
    QObject::connect(viewer.engine(), SIGNAL(quit()), &app, SLOT(quit()));//<----------------------新添加的
    viewer.show();

    return app.exec();
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.14
import QtQml 2.14//<-----------------------------------------------------------------------------新添加的

//Button的clicked事件响应onClicked

Rectangle {
    width: 640;
     height: 480;
    color: "gray";

    Button {
        text: "Quit";
        anchors.centerIn: parent;
        onClicked: {
            Qt.quit();
        }
    }
}

 

posted @ 2021-03-03 11:59  撑死算工伤吗  阅读(348)  评论(0编辑  收藏  举报