QStandardItemModel遍历查找搜索关键字
(1)findItems查找内容筛选项,只能查找显示的文字中是否包含该文字,但是
QList<QStandardItem*> findItems(const QString &text, Qt::MatchFlags flags = Qt::MatchExactly, int column = 0) const;
(2)match可以匹配的范围更广一些,不仅可以匹配显示内容,还可以匹配DisplayRole ,还可以查找CheckStateRole ,也就是勾选上的选项,不过目前测试QTreeView只能搜索第一级节点,子节点勾选上的无法匹配;即使Qt::MatchFlags设置成递归MatchRecursive也无法遍历子节点
enum ItemDataRole { DisplayRole = 0, DecorationRole = 1, EditRole = 2, ToolTipRole = 3, StatusTipRole = 4, WhatsThisRole = 5, // Metadata FontRole = 6, TextAlignmentRole = 7, BackgroundColorRole = 8, BackgroundRole = 8, TextColorRole = 9, ForegroundRole = 9, CheckStateRole = 10, // Accessibility AccessibleTextRole = 11, AccessibleDescriptionRole = 12, // More general purpose SizeHintRole = 13, InitialSortOrderRole = 14, // Internal UiLib roles. Start worrying when public roles go that high. DisplayPropertyRole = 27, DecorationPropertyRole = 28, ToolTipPropertyRole = 29, StatusTipPropertyRole = 30, WhatsThisPropertyRole = 31, // Reserved UserRole = 0x0100 };
Q_INVOKABLE virtual QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const;
QModelIndexList listindex = m_model->match(m_model->index(0,0), Qt::CheckStateRole, Qt::Checked, 1, Qt::MatchWrap | Qt::MatchRecursive); listindex= m_model->match(m_model->index(0, 0), Qt::DisplayRole, "1", 1, Qt::MatchContains | Qt::MatchRecursive);
(3)采用循环递归遍历的方式查找
int rootRowCount = m_model->rowCount(); for (int i = 0; i < rootRowCount; i++) { QModelIndex rootIndex = m_model->index(i, 0); RecursiveFindCheckedVideo(rootIndex, mapSelectVideo); }
递归函数
void RecursiveFindCheckedVideo(QModelIndex& parent, QMap<QString, QVariantMap>& mapSelectFile) { if (parent.isValid()) { int rowCount = m_model->rowCount(parent); for (int i = 0; i < rowCount; ++i) { QModelIndex childIndex = m_model->index(i, 0, parent); QStandardItem* pItem = m_model->itemFromIndex(childIndex); if (pItem) { QVariantMap info = pItem->data().toMap(); if (info.value("type") == "2")//视频文件 { mapSelectFile.insert(info.value("location").toString(), info); } else { RecursiveFindCheckedVideo(childIndex, mapSelectFile); // 递归遍历子项 } } } } }
自己开发了一个股票智能分析软件,功能很强大,需要的关注微信公众号:QStockView