Important: Please read the Qt Code of Conduct -

QTreeView loses highlight when clicking on empty space.

  • Hi,

    I have a QTabWidget with a QTableView widget in it that is populated via a SQL database. I have the behavior setup to highlight the whole row upon selection. If I click an empty space in the tab the TableView widget loses highlight.

    My Question is, does the selected row actually lose focus or is it technically still selected just not highlighted. I've tried trapping events with no luck. Second question is, is there a way to change this behavior.


  • Moderators

    @Chrisw01 Well it's easy to capture selectionChanged events, just override this function virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected).

    As for if the highlight goes away does the selection go away too.. I want to say that in the past I've seen the selection stay but the highlight disappear, but don't quote me on this. You want to test that by overriding the above function and doing a qDebug() when it changes. Then you can click to unhighlight and see what happens to your selection. To me it's more logical that the selection goes away too, but I vaguely remember having it stay. This memory is from at least 10 years ago, and Qt has come a long way since then. So definitely test it! :)

    Finally, to change this behavior, again override that selectionChanged function, and if selected is empty do not call the base implementation. This will prevent it from deselecting.

    Here is the code you need to do that:

    void MyTableView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
       if (selected.indexes().isEmpty())
       QAbstractView::selectionChanged(selected, deselected);

  • After Extensive testing, it appears nothing is fired when you click on a blank area of the widget. As for the Selection, it remains the same value whether the line is highlighted or not.

    Thanks for all your help..

  • @Chrisw01 you can use like this:

    void QTableViewNoSelect::mousePressEvent(QMouseEvent *e)
    QModelIndex inx = indexAt(e->pos());

Log in to reply