1、需求,创建一个树有多层结构,同一层按照插入顺序逆序排列;
ui.treeView->setHeaderHidden(true); //tree widget头标题是否显示,此处隐藏标题//ui.treeWidget->header()->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);ui.treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);//ui.treeView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);ui.treeView->header()->setCascadingSectionResizes(false);ui.treeView->header()->setStretchLastSection(true);m_modelTree = new QStandardItemModel(ui.treeView);m_TreeDelegate = new TreeTaskDelegate(ui.treeView);connect(m_TreeDelegate, &TreeTaskDelegate::signalBtClicked, this, &TreeTaskList::SlotTreeBtClicked);connect(m_TreeDelegate, &TreeTaskDelegate::signalEditFinish, this, &TreeTaskList::SlotEditFinish);ui.treeView->setItemDelegate(m_TreeDelegate);m_proxyModel = new QSortFilterProxyModel(ui.treeView);m_proxyModel->setSourceModel(m_modelTree);ui.treeView->setModel(m_proxyModel);m_modelTree->setColumnCount(1); // ui.treeView->setSortingEnabled(true);//ui.treeView->sortByColumn(0,Qt::AscendingOrder); m_proxyModel->setSortRole(Qt::UserRole+1);m_proxyModel->sort(0, Qt::DescendingOrder);ui.treeView->setIconSize(QSize(24, 24));ui.treeView->setColumnWidth(0, 300);
上面设置了一个排序按照角色Qt::UserRole+1去排序,排序方式为逆序排序;插入排序之后可以实现自动排序的功能;创建item的时候把创建时间设置到角色Qt::UserRole+1中去,然后QSortFilterProxyModel就会自动按照这个角色的值进行排序
QStandardItem *topItem = new QStandardItem();topItem->setCheckable(true);QString path = info.value("path").toString();topItem->setData( info.value("createtime").toString(),Qt::UserRole+1);info.insert("treeItem", QVariant::fromValue<QStandardItem *>(topItem));topItem->setData(info,Qt::UserRole);
如果批量导入,创建时间相同时,没有勾选时排好序,但是点击勾选的时候会出现重新排序,勾选和未勾选的分开排序,勾选的项跑到最下面去了,这不是我想要的排序方式,于是又给时间后面加上了一个rowcount值,在时间相同的情况,rouwcount肯定不一样,所以排序就不会变动
QStandardItem* videoFileItem = new QStandardItem();videoFileItem->setCheckable(true);//videoFileItem->setText(0, caseInfo.value("createtime").toString());QString path = caseInfo.value("path").toString();videoTaskInfo.insert("treeItem", QVariant::fromValue<QStandardItem*>(videoFileItem));for (auto it = videoTaskInfo.begin(); it != videoTaskInfo.end(); it++){caseInfo.insert(it.key(), it.value());}videoFileItem->setData( caseInfo,Qt::UserRole);videoFileItem->setData(caseInfo.value("createtime").toString()+"_"+QString::number(parant->rowCount()), Qt::UserRole+1);//时间相同时,勾选顺序会变动videoFileItem->setSizeHint( QSize(300, 40));QSortFilterProxyModel
方法2
重写QSortFilterProxyModel的lessthan函数,可以实现多个条件或者计算复杂的排序;
bool QTreeTaskFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const {QString left = source_left.data(Qt::UserRole+1).toString();QString right = source_right.data(Qt::UserRole).toString();return left <= right; }