How can I create a new window from within QML?

opatut picture opatut · Nov 30, 2011 · Viewed 23.3k times · Source

Is there a way to create a completely new window instance, as a child window of the main QML window in a QmlApplication?

// ChildWindow.qml
Rectangle {
    id: childWindow
    width: 100
    height: 100
    // stuff
}

// main.qml
Rectangle {
    id: window
    width: 1000
    height: 600

    MouseArea {
        anchors.fill: parent
        onClicked: createAWindow(childWindow);
    }
}

I am trying to avoid writing a Q_OBJECT class just for instanciating the new window within a new QmlApplicationViewer.

Answer

Kknd picture Kknd · Jun 25, 2014

You can do it by using Qt.createComponent. Example (using Qt 5.3):

main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    id: root
    width: 200; height: 200
    visible: true

    Button {
        anchors.centerIn: parent
        text: qsTr("Click me")

        onClicked: {
            var component = Qt.createComponent("Child.qml")
            var window    = component.createObject(root)
            window.show()
        }
    }
}

Child.qml

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    id: root
    width: 100; height: 100

    Text {
        anchors.centerIn: parent
        text: qsTr("Hello World.")
    }
}