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

用 C++ 打造 QML TreeView 的資料模型(二):加入節點與層次結構

編輯:關於 Android 開發

上一篇把二維表模型跑通了,這一篇要把它改造成能表達層次關係的樹狀模型。核心思路是:不再用 QList 存資料列,而是引入一個節點類別,讓每筆資料自己記住父子關係。

第一步:設計 TreeNode

class TreeNode;

typedef TreeNode* TreeNodePtr;

class TreeNode
{
public:
    explicit TreeNode();

    TreeNodePtr parent() const;
    void setParent(const TreeNodePtr p); // 設置父節點,根節點的父節點為 NULL
    void appendNode(TreeNodePtr node);
    void removeNode(int row);

    void setData(int role, QVariant value);
    QVariant data(int role);

    QList<TreeNodePtr> childs; // 保存子節點指針

private:
    TreeNodePtr mParent = NULL;      // 父節點
    QHash<int, QVariant> mRecord;    // 一個節點保存一列資料,key 為 role
};

實作起來沒什麼難度:

TreeNodePtr TreeNode::parent() const
{
    return mParent;
}

void TreeNode::setParent(const TreeNodePtr p)
{
    this->mParent = p;
}

void TreeNode::appendNode(TreeNodePtr node)
{
    childs.append(node);
}

void TreeNode::removeNode(int row)
{
    childs.removeAt(row);
}

QVariant TreeNode::data(int role)
{
    return mRecord[role];
}

void TreeNode::setData(int role, QVariant value)
{
    mRecord[role] = value;
}

第二步:改造模型定義

QList 存不了樹,把它換掉,改成維護根節點清單,並補上一個私有的掛載輔助函式:

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<TreeNodePtr> mRootEntrys;  // 保存根節點

    void _addEntryNode(TreeNodePtr node, TreeNodePtr parent = 0);
};
void SqlMenuEntry::_addEntryNode(TreeNodePtr node, TreeNodePtr parent)
{
    if (parent == NULL) {
        mRootEntrys.append(node);
    } else {
        node->setParent(parent);
        parent->appendNode(node);
    }
}

第三步:餵資料進去

新增或清空整棵樹之前,用 beginResetModel() / endResetModel() 把這段操作包起來,View 才會正確刷新:

beginResetModel();

auto node = new TreeNode();
node->setData(nameRole, "parent 1");
node->setData(iconRole, "parenticon1");
_addEntryNode(node);              // 加入第一個根節點

auto subNode = new TreeNode();
subNode->setData(nameRole, "child1");
_addEntryNode(subNode, node);     // 加入子節點

endResetModel();

第四步:讓五個介面認得層次

rowCount:parent 有效時回傳該節點的子節點數,否則回傳根節點數。

int SqlMenuEntry::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        // 節點資訊在 index() 時已存進 QModelIndex 的 internalPointer
        TreeNodePtr parentNode = (TreeNodePtr)parent.internalPointer();
        return parentNode->childs.size();
    }
    return mRootEntrys.size();
}

index:把對應的節點指標存進 internalPointer,後續函式才有辦法取回節點資料。

QModelIndex SqlMenuEntry::index(int row, int column, const QModelIndex &parent) const
{
    if (!parent.isValid()) {
        if ((row >= 0) && (row < mRootEntrys.size())) {
            return createIndex(row, column, mRootEntrys.at(row));
        }
    } else {
        TreeNodePtr parentNode = (TreeNodePtr)parent.internalPointer();
        if ((row >= 0) && (row < parentNode->childs.size())) {
            return createIndex(row, column, parentNode->childs[row]);
        }
    }
    return QModelIndex();
}

parent:回傳某個節點的父節點索引,根節點回傳空索引。

QModelIndex SqlMenuEntry::parent(const QModelIndex &child) const
{
    TreeNodePtr node = (TreeNodePtr)child.internalPointer();
    if (node == NULL || node->parent() == NULL) {
        return QModelIndex(); // 根節點沒有 parent
    }
    return createIndex(0, 0, node->parent());
}

data:直接從節點取出對應 role 的值。

QVariant SqlMenuEntry::data(const QModelIndex &index, int role) const
{
    TreeNodePtr node = (TreeNodePtr)index.internalPointer();
    if (node == NULL) {
        return QVariant();
    }
    return node->data(role);
}

QML 端:換成 TreeView

TreeView {
    anchors.fill: parent

    TableViewColumn {
        title: "Name"
        role: "name"
    }

    TableViewColumn {
        title: "Entry"
        role: "icon"
    }

    model: MenuEntryModel { }
}

到這裡的關鍵要點

整份改造其實圍繞一個機制運轉:QModelIndex 的 internalPointer。View 手上永遠只有 modelIndex,模型必須靠它把「這個索引對應哪個節點」偷渡進去,index() 負責寫入,rowCount()、parent()、data() 負責讀出。把這條線看懂,Qt 的 Model/View 設計就不再神祕。

接下來還要補上資料的新增、刪除與更新,以及對應的 beginInsertRows / endInsertRows 通知機制,留待後續補充。

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