在Qt帮助中,模型/视图教程-3.2使用选择中有一个示例。资源代码位于Qt\Qt5.9.1\Examples\Qt-5.9.1\widgets\tutorials\modelview\7_selections中。
我无法理解while(seekRoot.parent() != QModelIndex())
中的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);
}
空的QModelIndex()
构造函数表示无效(即不存在(的QModelIndex
:
创建一个新的空模型索引。这种类型的模型索引用于指示模型中的位置无效。
因此seekRoot.parent() != QModelIndex()
检查seekRoot
是否有父级(即其父级不是无效的(。
它也可以(更清楚地(写成seekRoot.parent().isValid()
(参见QModelIndex::isValid
(。
默认构造函数QModelIndex()
创建一个临时无效索引,seekRoot.parent()
调用的输出与之相比。换句话说,此表达式检查父索引是否有效。