點擊上方藍字可直接關注!方便下次閱讀。如果對你有幫助,可以點個在看,讓它可以幫助到更多老鐵~
一、概述
接着之前的話題繼續!
如果把之前的QTableView改成QTreeView,我們在不改變Model的情況下可以直接得到一個沒有結構層次的“樹”;因爲QAbstractTableModel不具有數據層次結構,如果我們想要實現有層次的數據結構,需要使用QStandardItemModel
該模型。爲了顯示一棵樹,QStandardItemModel需要使用QStandardItem來進行填充。
下面梳理下幾個類的關係:
QObject
||
QAbstractItemModel
||
QAbstractTableModel(Table層次結構) QStandardItemModel(Tree層次結構)
如果以後構建自己的代碼庫時,各個模塊劃分的越詳細則越方便複用。
二、程序舉例
1. 使用QStandardItemModel構建Tree
以Qt自帶的treeview來說明
//實例化model
standardModel = new QStandardItemModel ;
//QStandardItem 節點數據
QList<QStandardItem *> preparedRow =prepareRow("first", "second", "third");
// root 節點
QStandardItem *item = standardModel->invisibleRootItem();
//root 節點添加數據
item->appendRow(preparedRow);
//又一個QStandardItem 節點數據
QList<QStandardItem *> secondRow =prepareRow("111", "222", "333");
//在first節點上再添加一個數據
preparedRow.first()->appendRow(secondRow);
//view 設置model並全部展開
treeView->setModel(standardModel);
treeView->expandAll();
//添加數據節點的函數
QList<QStandardItem *> MainWindow::prepareRow(const QString &first,
const QString &second,
const QString &third)
{
QList<QStandardItem *> rowItems;
rowItems << new QStandardItem(first);
rowItems << new QStandardItem(second);
rowItems << new QStandardItem(third);
return rowItems;
}
效果圖如下:
2. 獲得所選Item的內容以及層級
有了上面的基礎,接下來進行擴展:
當treeView的Item被選中時,treeView 的selectionModel會發出selectionChanged的信號,將該信號與槽函數進行連接,在槽函數中我們可以通過index獲得所選Item的內容;通過頂層節點沒有parent的特點來計算所選Item的層級。
主要代碼如下:
//信號函數 連接信號與槽
QItemSelectionModel *selectionModel= treeView->selectionModel();
connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)),this, SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &)));
//槽函數如下
void MainWindow::selectionChangedSlot(const QItemSelection & /*newSelection*/, const QItemSelection & /*oldSelection*/)
{
//get the text of the selected item
const QModelIndex index = treeView->selectionModel()->currentIndex();
QString selectedText = index.data(Qt::DisplayRole).toString();
//find out the hierarchy level of the selected item
int hierarchyLevel=1;
QModelIndex seekRoot = index;
while(seekRoot.parent() != QModelIndex())
{
seekRoot = seekRoot.parent();
hierarchyLevel++;
}
QString showString = QString("%1, Level %2").arg(selectedText)
.arg(hierarchyLevel);
setWindowTitle(showString);
}
效果如下:
默認title
更改後的title及層級
三、小結
①Model/View中要想通過TreeView顯示樹型結構,需要在QStandardItemModel中組織樹形數據結構
②通過index計算樹形結構層級的方式
③通過index可以Item的內容
④使用**View時必須設置Model,因爲Model中存儲着數據結構
學不可以已
20200202 於 北京門頭溝。