简体   繁体   中英

How to close a window in QML/Javascript code (with C++ code involved)?

I have a QML window declared for example in MyWindow.qml:

Item {
    id: thisWindow
    width: 500
    height: 140
    ... sub-items that declare the UI of the window ...

And a C++ class that instantiates that QML:

class MyWindow : public QQuickView
...
MyWindow::MyWindow() {
    setSource(QUrl("qrc:/MyWindow.qml"));
    setFlags(Qt::WindowFlags(Qt::Popup));
}

How do I close that window from Javascript/QML code? I can't call thisWindow.close(), because it's just an item type in the hierarchy.

The easiest option is to export the QQuickView to the .qml with setContextProperty() :

#include <QQmlEngine>
#include <QQmlContext>

// ...
{
    engine()->rootContext()->setContextProperty("view", this);
    setSource(QUrl("qrc:/MyWindow.qml"));
    setFlags(Qt::WindowFlags(Qt::Popup));
}

And then in QML you can use:

view.close()

You don't need c++ to do that. You can do it with the window attached property straight from QML.

//other imports
import QtQuick.Window 2.2

Item {
    id: thisWindow
    width: 500
    height: 140
    //... sub-items that declare the UI of the window ...
    MouseArea {
        anchors.fill: parent
        onClicked: Window.window.close()
     }
}

使用Qt全局对象并按照此处的说明进行操作: http : //doc.qt.io/qt-5/qml-qtqml-qt.html#quit-method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM