[英]How to close a window in QML/Javascript code (with C++ code involved)?
I have a QML window declared for example in MyWindow.qml: 我在MyWindow.qml中声明了一个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: 还有一个实例化该QML的C ++类:
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? 如何从Javascript / QML代码关闭该窗口? I can't call thisWindow.close(), because it's just an item type in the hierarchy.
我不能调用thisWindow.close(),因为它只是层次结构中的一个项目类型。
The easiest option is to export the QQuickView
to the .qml with setContextProperty()
: 最简单的方法是使用
setContextProperty()
将QQuickView导出到QQuickView
:
#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: 然后在QML中,您可以使用:
view.close()
You don't need c++ to do that. 您不需要c ++就能做到。 You can do it with the
window
attached property straight from QML. 您可以使用直接来自QML的
window
附加属性来执行此操作。
//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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.