Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Selecting a row in QTreeView programmatically



  • Hi all,

    I have been trying to select a row (also go to that row) from a qtreeview problematically but could not achieve it.
    I know there are already couple of questions for the same but none of them could help me to get what I expect.

    I have tried below codes :

    QModelIndex idx= m_pOutlineTree->model()->index(3, 0, index_view);
    //index_view is my root QModelIndex of complete qtreeview and 3,0 is the row no I have to go to.
    
    /*1.*/ myTreeView->setCurrentIndex(idx);
    
    /*2.*/myTreeView->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
    

    But none of the above works as intended.

    Could anyone please guide me what I am missing or a better way to achieve this.


  • Qt Champions 2019

    Did you check if idx is acutally valid?



  • Thank you for the reply.
    Yes, Its valid. I tried to print the data, row and column to check if it actually the one i intent it to be. And its fine.

    QVariant data = m_pOutlineTree->model()->data(idx);
            QString text = data.toString();
            qDebug()<<text + "  " + QString::number(idx.row()) + "  " + QString::number(idx.column());
    

  • Qt Champions 2019

    @NoumanYosuf said in Selecting a row in QTreeView programmatically:

    index_view is my root QModelIndex

    I'm asking because this somehow makes no sense - when it's the root index then index_view is a simple, invalid QModelIndex.
    Please check that QTreeView::currentIndex() actually returns your index.



  • currentIndex() returns a valid index.I am not sure where is the mistake.


Log in to reply