zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Qml自定义ListModel(视频)

视频 自定义 qml
2023-06-13 09:17:29 时间

❝创建C++的列表模型,并注册到Qml中使用。❞

1. 自定义ListModel

  MyListModel继承于QAbstractListModel。

/* 创建一个列表模型 */
class MyListModel : public QAbstractListModel
{
    Q_OBJECT
public:
    MyListModel()
    {
        m_stringList = QStringList{"1", "2", "3"};
    }

    int rowCount(const QModelIndex &parent) const
    {
        return m_stringList.count();
    }

    QVariant data(const QModelIndex &index, int role) const
    {
        return m_stringList.at(index.row());
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role)
    {
        m_stringList[index.row()] = value.toString();

        emit dataChanged(index, index);
        return true;
    }

    /* 创建数据访问的别名。(可用于Qml使用) */
    QHash<int, QByteArray> roleNames() const
    {
        QHash<int, QByteArray> roles;
        roles[Qt::UserRole] = "modelData";
        return roles;
    }

private:
    QStringList m_stringList;
};

2. 注册到Qml中

/* 注册Qml类型 */
qmlRegisterType<MyListModel>("MyListModel", 1, 0, "MyListModel");

3. 使用

  声明MyListModel到Qml中,并创建其实例MyListModel { id: myListModel }。ListView的代理(delegate)通过设置modelData改变其myListModel对象的QStringList内容。

import MyListModel 1.0
...
ListView {
    id: listView
    anchors.fill: parent
    model: MyListModel { id: myListModel }
    delegate: Rectangle {
        width: 300
        height: 100

        Row {
            Text {
                anchors.verticalCenter: parent.verticalCenter
                width: 200
                text: modelData
            }

            Rectangle {
                width: 50
                height: 50
                color: mouseArea.pressed ? "lightgray" : "lightblue"

                Text {
                    anchors.centerIn: parent
                    /* 改变数据(随机数) */
                    text: "改变"
                }

                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    onClicked: {
                        modelData = Math.random()
                    }
                }
            }
        }
    }
}
...