Qt Model View TreeView及对应Model

点击上方蓝字可直接关注!方便下次阅读。如果对你有帮助,可以点个在看,让它可以帮助到更多老铁~

一、概述

 

接着之前的话题继续!

 

如果把之前的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的内容以及层级

有了上面的基础,接下来进行扩展:

 

treeViewItem被选中时,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 于 北京门头沟。

发布了91 篇原创文章 · 获赞 94 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ACK_ACK/article/details/104151647