In Qt help, there is an example in Model/View Tutorial - 3.2 Working with Selections. The resource codes are in Qt\Qt5.9.1\Examples\Qt-5.9.1\widgets\tutorials\modelview\7_selections.
I cannot understand what is QModelIndex() in while(seekRoot.parent() != QModelIndex())
.
It looks like a constructor of QModelIndex, but what's the usage here? It returns a new empty model index? Or it is a function of MainWindow? It seems impossible.
Where does it come from? And what is the return value?
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);
}
The empty QModelIndex()
constructor indicates an invalid (i.e. non existing) QModelIndex
:
Creates a new empty model index. This type of model index is used to indicate that the position in the model is invalid.
So seekRoot.parent() != QModelIndex()
checks if seekRoot
has a parent (i.e. its parent is not invalid).
It could also be written (more clearly) as seekRoot.parent().isValid()
(see QModelIndex::isValid
).