0 c++ qt model-view
在 Qt 帮助中,模型/视图教程 - 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);
}
Run Code Online (Sandbox Code Playgroud)
空QModelIndex()构造函数表示无效(即不存在)QModelIndex:
创建一个新的空模型索引。此类模型索引用于指示模型中的位置无效。
因此seekRoot.parent() != QModelIndex()检查是否seekRoot有父级(即其父级不是无效的)。
它也可以写成(更清楚)为seekRoot.parent().isValid()(参见QModelIndex::isValid)。