How can QT implement a side navigation bar in QML?

要实现QML侧边导航栏,可以使用Column布局和ListView控件来实现。以下是一个简单的示例代码:

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 800
    height: 600

    ColumnLayout {
        anchors.fill: parent

        ListView {
            model: ListModel {
                ListElement { text: "Option 1" }
                ListElement { text: "Option 2" }
                ListElement { text: "Option 3" }
            }

            delegate: Item {
                width: parent.width
                height: 50

                Rectangle {
                    color: ListView.isCurrentItem ? "lightblue" : "white"
                    width: parent.width
                    height: parent.height

                    Text {
                        text: model.text
                        anchors.centerIn: parent
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            listView.currentIndex = index
                        }
                    }
                }
            }
        }

        Rectangle {
            Layout.fillHeight: true
            Layout.fillWidth: true
            color: "lightgrey"
        }
    }
}

In this example, the ColumnLayout layout is used to arrange the ListView and other content. The ListView contains a simple ListModel to display navigation options. Each option is displayed using an Item, and clicking on an option can toggle its selection. Additionally, a gray Rectangle is used to represent the main content area in the example.

By doing this, it’s easy to create a simple QML side navigation bar. You can customize the style and functionality according to your own needs.

bannerAds