有没有办法向QListView添加部分?

问题描述 投票:0回答:1

我正在使用 Qt5.2 和 C++ 来实现应用程序,需要显示一个列表,其中包含类似于下面的示例图片的部分:


(来源:ngo-hung.com

请注意,我没有实现移动应用程序,并且不需要右侧的字母索引。除了实现 QTreeView 之外,还有什么建议可以实现这一点吗? 谢谢。

qt qlistview
1个回答
-1
投票

QML 中的 ListView 内置了对部分的支持。在下面的示例中,我有一个 ListModel,其中该部分是通过“sec”角色定义的。 ListModel 定义了一个部分委托以及一个联系人委托:

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
    title: "ListView sections demo"
    header: Frame {
        background: Rectangle { color: "red" }
        RowLayout {
            width: parent.width
            AppIconButton { icon.source: "address-book-32.svg" }
            Text {
                Layout.fillWidth: true
                text: qsTr("All Contacts")
                color: "white"
            }
        }
    }
    ListView {
        anchors.fill: parent
        model: contacts
        delegate: Frame {
            width: ListView.view.width
            RowLayout {
                width: parent.width
                AppIconButton {
                    icon.source: "https://raw.githubusercontent.com/Esri/calcite-ui-icons/master/icons/user-32.svg"
                    icon.color: "green"
                }
                ColumnLayout {
                    Layout.fillWidth: true
                    Text {
                        Layout.fillWidth: true
                        text: fn
                    }
                    Text {
                        Layout.fillWidth: true
                        text: qsTr("Full name: %1 %2").arg(fn).arg(sn)
                    }
                }
            }
        }
        section.property: "sec"
        section.delegate: Frame {
            width: ListView.view.width
            background: Rectangle { color: "lightsteelblue" }
            Text {
                text: section
                color: "white"
            }
        }
    }
    ListModel {
        id: contacts
        ListElement { sec: "B"; fn: "Branda"; sn: "Respass" }
        ListElement { sec: "C"; fn: "Chana"; sn: "Hollin" }
        ListElement { sec: "D"; fn: "Delisa"; sn: "Deak" }
        ListElement { sec: "D"; fn: "Demetrius"; sn: "Zona" }
        ListElement { sec: "D"; fn: "Dwain"; sn: "Mark" }
    }
}

// AppIconButton.qml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Item {
    id: iconButton
    property alias icon: button.icon
    Layout.preferredWidth: icon.width
    Layout.preferredHeight: icon.height
    Button {
        id: button
        anchors.centerIn: parent
        background: Item {}
        icon.width: 32
        icon.height: 32
        icon.color: "white"
    }
}

// address-book-32.svg : https://raw.githubusercontent.com/Esri/calcite-ui-icons/master/icons/address-book-32.svg

您可以在线尝试!

© www.soinside.com 2019 - 2024. All rights reserved.