QML入门教程03:MVC模式

QListView采用MVC模式,QListView控件用于显示,QAbstractItemModel用于保存数据。这个机制同样可以用于QML。

M

头文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#ifndef MYMODEL_H
#define MYMODEL_H

#include <QAbstractListModel>
#include <QList>

class MyModel : public QAbstractListModel
{
Q_OBJECT

public:
explicit MyModel(QObject *parent = nullptr);

enum {
NameRole = Qt::UserRole + 1,
AgeRole,
EmailRole
};

// 重写以下几个虚函数
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;

private:
struct Person {
QString name;
int age;
QString email;
};

QList<Person> m_persons;
};

#endif // MYMODEL_H

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "mymodel.h"
#include "mymodel.h"

MyModel::MyModel(QObject *parent)
: QAbstractListModel(parent)
{
// 初始化一些数据
m_persons.append({"Alice", 25, "alice@example.com"});
m_persons.append({"Bob", 30, "bob@example.com"});
m_persons.append({"Charlie", 35, "charlie@example.com"});
}
int MyModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_persons.count();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= m_persons.count() || index.row() < 0)
return QVariant();
const Person &person = m_persons[index.row()];
if (role == NameRole)
return person.name;
else if (role == AgeRole)
return person.age;
else if (role == EmailRole)
return person.email;
return QVariant();
}
QHash<int, QByteArray> MyModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[AgeRole] = "age";
roles[EmailRole] = "email";
return roles;
}

V

显示部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.5

Window {
visible: true
width: 480
height: 800
title: qsTr("Hello World")

ListView {
anchors.fill: parent
model: myModel
delegate: Item {
width: parent.width
height: 60
Column {
Text { text: name }
Text { text: age }
Text { text: email }
}
}
}
}

QML入门教程03:MVC模式
https://blog.jackeylea.com/qt/qml/qml-mvc-mode-with-cpp/
作者
JackeyLea
发布于
2024年12月28日
许可协议