在Qt帮助中,在Model/View教程中有一个示例- 3.2使用选择。资源代码在Qt\Qt5.9.1\Examples\Qt-5.9.1\widgets\tutorials\modelview\7_selections.中。
我不明白QModelIndex()在while(seekRoot.parent() != QModelIndex())中是什么。它看起来像QModelIndex的构造函数,但是这里的用法是什么呢?它返回一个新的空模型索引吗?还是MainWindow的一个函数?这似乎不可能。
它是从哪里来的?返回值是多少?
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);
}发布于 2020-07-16 10:05:06
空QModelIndex()构造函数指示无效(即不存在) QModelIndex
创建一个新的空模型索引。这种类型的模型索引用于表示模型中的位置无效。
因此,seekRoot.parent() != QModelIndex()检查seekRoot是否有父级(即它的父级不无效)。
它也可以写成(更清楚)为seekRoot.parent().isValid() (参见QModelIndex::isValid)。
发布于 2020-07-16 10:03:47
默认构造函数QModelIndex()创建一个临时无效索引,与之相比,seekRoot.parent()调用的输出。换句话说,该表达式检查父索引是否有效。
https://stackoverflow.com/questions/62932143
复制相似问题