如何在QML中创建新窗口?

问题描述 投票:14回答:2

是否有一种方法可以创建一个全新的窗口实例,作为QmlApplication中QML主窗口的子窗口?

// 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);
    }
}

[我试图避免只为了在新的Q_OBJECT中实例化新窗口而编写QmlApplicationViewer类。

window qml qobject
2个回答
1
投票

无法仅使用内置的QML功能创建顶级窗口。

但是Qt Labs上有一个名为Desktop Components的项目,其中除其他外还包含Window component,可用来创建新的顶层窗口。


31
投票

您可以通过使用Qt.createComponent来完成。示例(使用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.")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.