简体   繁体   中英

Where does QModelIndex() come from in seekRoot.parent() != QModelIndex();

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 (ie 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 (ie its parent is not invalid).

It could also be written (more clearly) as seekRoot.parent().isValid() (see QModelIndex::isValid ).

The default constructor QModelIndex() creates a temporary invalid index the output of seekRoot.parent() call compared with. In other words, this expression checks whether the parent index is valid or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM