- A+
在 QTreeView 中,可以通过 QModelIndex 对象来访问模型中的数据。如果你有每个项目的唯一标识符,那么可以根据这个标识符来获取相应的 QModelIndex 对象。
首先,当你创建 QStandardItemModel 时,你需要为每个项目设置一个唯一的标识符。例如:
- QStandardItemModel model;
- for (int i = 0; i < 4; ++i) {
- QList<QStandardItem*> items;
- for (int j = 0; j < 3; ++j) {
- QString text = QString("item %1-%2").arg(i).arg(j);
- // 设置标识符
- QStandardItem* item = new QStandardItem(text);
- item->setData(QString("%1-%2").arg(i).arg(j), Qt::UserRole + 1);
- items.append(item);
- }
- model.appendRow(items);
- }
上述代码中,在每个 QStandardItem 对象中,我们使用 setData() 函数为其添加了一个唯一的标识符,它位于 Qt::UserRole + 1 的位置。
接下来,我们可以通过以下代码找到具有特定 id 值的项的 QModelIndex 对象:
- // 查找具有特定 id 值的项
- QString targetId = "2-1"; // 需要查找项的标识符
- QModelIndex curIndex = model.index(0, 0); // 从第一个项开始遍历
- while (curIndex.isValid()) {
- // 获取当前项的标识符并与目标标识符进行比较
- QString curId = curIndex.data(Qt::UserRole + 1).toString();
- if (curId == targetId) {
- // 如果找到了目标项,跳出循环
- break;
- }
- // 如果当前项没有子项,遍历下一个同级项
- if (!model.hasChildren(curIndex)) {
- curIndex = model.index(curIndex.row() + 1, 0, curIndex.parent());
- }
- // 如果有子项,转到第一个子项
- else {
- curIndex = model.index(0, 0, curIndex);
- }
- }
- if (curIndex.isValid()) {
- // 如果找到了目标项,输出它的行列索引和父索引
- int row = curIndex.row();
- int column = curIndex.column();
- QModelIndex parentIndex = curIndex.parent();
- qDebug() << "row:" << row << "column:" << column << "parentIndex:" << parentIndex;
- } else {
- // 没有找到目标项
- qDebug() << "not found";
- }
上述代码中,我们使用 index() 函数获取从模型中获取 第一行第一列 的 QModelIndex 对象作为起始点,然后遍历整个模型,直到找到具有指定 id 值的项。在每次迭代中,我们使用 data() 函数获取当前项的标识符,如果它与目标标识符相匹配,则跳出循环。在找到目标项时,我们使用 QModelIndex 的 row()、column() 和 parent() 函数获取行列索引和父索引。
需要注意的是,上述示例只是一种实现方式,你可能会使用不同的算法或数据结构来查找 QTreeView 中的项。在实际开发中,还应该注意代码的错误处理和性能问题。