Qt5 QtQuick 2.0(Qt Quick Application)在一个窗口中切换视图(qml文件)

kon*_*rad 5 c++ qt qml qt-quick

在传统的Qt(QWidget)中,我有一个QMainWindow和一些带有内容的动态创建的QWidget,并且我更改了它们以使它们在主窗口中可见。当我有几个qml文件并且想要例如在单击按钮时能够在它们之间切换时,实现方法是什么?

And*_*ich 1

解决这个问题至少有3种选择:

  1. 您可以使用为此目的准备好的组件StackView。重点是您将同时创建 2 个组件,并且可以通过单击按钮来更改它们。

例子:

import QtQuick 2.12
import QtQuick.Controls 2.5

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("Stack")

    header: ToolBar {
        contentHeight: toolButton.implicitHeight

        ToolButton {
            id: toolButton
            text: stackView.depth > 1 ? "\u25C0" : "\u2630"
            font.pixelSize: Qt.application.font.pixelSize * 1.6
            onClicked: {
                if (stackView.depth > 1) {
                    stackView.pop()
                } else {
                    drawer.open()
                }
            }
        }

        Label {
            text: stackView.currentItem.title
            anchors.centerIn: parent
        }
    }

    Drawer {
        id: drawer
        width: window.width * 0.66
        height: window.height

        Column {
            anchors.fill: parent

            ItemDelegate {
                text: qsTr("Page 1")
                width: parent.width
                onClicked: {
                    stackView.push("Page1Form.qml")
                    drawer.close()
                }
            }
            ItemDelegate {
                text: qsTr("Page 2")
                width: parent.width
                onClicked: {
                    stackView.push("Page2Form.qml")
                    drawer.close()
                }
            }
        }
    }

    StackView {
        id: stackView
        initialItem: "HomeForm.qml"
        anchors.fill: parent
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 这里使用Loader会在执行过程中动态加载文件,这种方法的缺点是如果经​​常切换的话会比较耗时。

例子:

import QtQuick 2.0

Item {
    width: 200; height: 200

    Loader { id: pageLoader }

    MouseArea {
        anchors.fill: parent
        onClicked: pageLoader.source = "Page1.qml"
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您可以在 C++ 中创建一个类,该类将被赋予一个已初始化的 QML 对象到一个空的 qml 表单。因此,mono 将各个组件放入库中并将它们用作插件(使用 qqmlcomponent)。