Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qml

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.

like image 433
Juster Avatar asked Apr 08 '26 18:04

Juster


2 Answers

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()
     }
}
like image 136
GrecKo Avatar answered Apr 11 '26 06:04

GrecKo


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()
like image 38
eyllanesc Avatar answered Apr 11 '26 06:04

eyllanesc