opatut
opatut

Reputation: 6864

How can I create a new window from within QML?

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.

Upvotes: 23

Views: 33875

Answers (3)

Vladimir Serdyuk
Vladimir Serdyuk

Reputation: 41

With @Kknd's approach we had a problem that child window didn't respond to mouse events. We are using Qt 6.6.1. The following worked:

main.qml

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

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

        onClicked: {
            var window = child_window_comp.createObject(root)
            window.show()
        }
    }
    
    Component {
        id: child_window_comp
        Child {
        }
    }
}

Child.qml

import QtQuick
import QtQuick.Controls

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

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

Upvotes: 0

Kknd
Kknd

Reputation: 3217

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.")
    }
}

Upvotes: 49

sepp2k
sepp2k

Reputation: 370465

There is no way to create top-level windows using only built-in QML functionality.

However there's a project on Qt Labs called Desktop Components, which among other things contains a Window component, which allows you to create new top-level windows.

Upvotes: 3

Related Questions