Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 C++ 打造 QML TreeView 的資料模型(一):從 QAbstractItemModel 談起

編輯:關於 Android 開發

QML 中的 ListView、TableView、GridView 若只用 ListModel 餵資料,很快會撞到天花板:讀不到本機檔案系統、接不上既有的 SQL 資料庫。實務上的做法是反過來——用 C++ 實作資料模型,把展示與編輯交給 QML。本文先從最基礎的 QAbstractItemModel 開始。

為什麼是 QAbstractItemModel

Qt 提供 QAbstractTableModel、QSQLTableModel 等高階模型,但它們全都繼承自 QAbstractItemModel。理解這一支抽象類別的介面與運作機制,等於掌握了整個 Qt Model/View 體系的底層規則。

它是抽象類別,要能實例化,至少必須實作這五個方法:

int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QModelIndex parent(const QModelIndex &child) const;

關鍵差異:QML 用 Role 而非 Column 取資料

這點和 QWidget 體系很不一樣。在 QML 中,TableViewColumn 透過 role 屬性對應模型欄位:

TableView {
    id: tableView1
    anchors.fill: parent

    TableViewColumn {
        width: 50
        title: ""
        role: "tagging"
    }

    TableViewColumn {
        width: 80
        title: "操作"
        role: "name"
    }
}

View 會呼叫模型的 roleNames() 來得知有哪些 role 可用。因此除了那五個純虛函式,還必須多實作一個:

QHash<int, QByteArray> roleNames() const;

完整的類別定義

class SqlMenuEntry : public QAbstractItemModel, public QQmlParserStatus
{
    Q_OBJECT
public:
    explicit SqlMenuEntry(QObject *parent = 0);
    ~SqlMenuEntry();

    enum MenuEntryRoles {
        idRole = Qt::UserRole + 1,
        nameRole,
        defaultEntryRole,
        customEntryRole,
        iconRole,
        iconHoverRole
    };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QModelIndex parent(const QModelIndex &child) const;
    QHash<int, QByteArray> roleNames() const;

private:
    QHash<int, QByteArray> mRoleNames;
    QList<QHash<int, QVariant>> mRecords; // 真正的資料存放處
    // 注意:QList 只能保存二維資料,無法表達樹狀節點,此處僅作示範
};

roleNames() 的實作非常直接,回傳成員即可:

QHash<int, QByteArray> SqlMenuEntry::roleNames() const
{
    return mRoleNames;
}

而 mRoleNames 在建構子中初始化:

SqlMenuEntry::SqlMenuEntry(QObject *parent)
    : QAbstractItemModel(parent)
{
    mRoleNames[nameRole] = "name";
    mRoleNames[idRole] = "menuid";
    mRoleNames[iconRole] = "icon";
    mRoleNames[defaultEntryRole] = "default";
    mRoleNames[iconHoverRole] = "iconHover";
}

完成之後,QML 端就能直接用這些字串名稱取資料:

ListView {
    model: MenuEntryModel { }
    delegate: Item {
        Column {
            Text { text: name }
            Text { text: icon }
        }
    }
}

二維表的五個介面怎麼寫

int SqlMenuEntry::rowCount(const QModelIndex &parent) const
{
    return mRecords.size();
}

int SqlMenuEntry::columnCount(const QModelIndex &parent) const
{
    // QML 不用列取資料,預設回傳 1;
    // 若不回傳 1,View 會判定為空表而不抓資料
    return 1;
}

QModelIndex SqlMenuEntry::index(int row, int column, const QModelIndex &parent) const
{
    if ((row >= 0) && (row < mRecords.size())) {
        return createIndex(row, column);
    }
    return QModelIndex(); // 回傳無效的空索引
}

QModelIndex SqlMenuEntry::parent(const QModelIndex &child) const
{
    return QModelIndex(); // 二維表的列沒有 parent 節點
}

QVariant SqlMenuEntry::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        return mRecords[index.row()][role];
    }
    return QVariant();
}

mRecords 的內容可依需求產生,例如用 QSqlQuery 從資料庫取回後逐列填入:

QHash<int, QVariant> row;
row[nameRole] = "name1";
row[iconRole] = "icon1";
mRecords.append(row);

註冊給 QML 使用

qmlRegisterType<SqlMenuEntry>("com.limutech.tv", 1, 0, "MenuEntryModel");

註冊後即可在 QML 中建立實例:

import com.limutech.tv 1.0

MenuEntryModel {
    id: menuEntryModel
}

ListView {
    model: menuEntryModel
    // delegate ...
}

View 抓資料的實際流程

  1. 呼叫 rowCount() 並傳入空 parent,取得根節點的列數。
  2. 呼叫 columnCount() 並傳入空 parent,取得根節點的欄數。
  3. 逐列逐欄呼叫 index(),傳入列號、欄號與空 parent,取得根層級的 QModelIndex。
  4. 以回傳的 modelIndex 作為 parent,再取該列的 rowCount 與 columnCount;若大於 0,代表還有子節點。
  5. 呼叫 roleNames() 取得可用的 role 清單。
  6. 以 modelIndex 與 role 為參數呼叫 data(),交由對應的 delegate 呈現。

看過這六步就明白:要讓 TreeView 正常顯示,二維表模型並不夠——必須處理 parent 不為空的情況,模型本身也得能承載樹狀資料。下一篇就來動這場手術。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved