Important: Please read the Qt Code of Conduct -

QTreeView: Select One or None - close, but no cigar.

  • So, I'm keen to make a QTreeView select a single index to pick an item, or select nothing by clicking empty space. I found this very helpful hint:


    Which got me pretty far. My equivalent method in C++ is:

    void DeselectableTreeView::mousePressEvent(QMouseEvent* event)

    emit selection_cleared();

    However, adding the if(!this->selectedIndexes().count()){...} line causes windows to trigger a breakpoint:

    HEAP[LMGM.exe]: Invalid address specified to RtlValidateHeap( 00210000, 02798DE8 )

    Now, keep in mind, this signal isn't connected to anything. the code is simply there. If I remove the code, the application runs as expected. Any idea's as to how to solve this, what I've done wrong, or a more desirable way to implement the desired behavior?

  • A slight addendum: I need to know when 'nothing' is selected, hence the signal. As a work around, I'm picking up on the escape key which is nice (and will stay) but I'd really like the ability to de-select by clicking empty space.

  • I would change the logic into something like

    QModelIndex index = indexAt(event->pos());
    if (index.isValid()) {
    selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
    } else {

    By the way, you can connect a slot the QItemSelecitonModel::selectionChanged signal (the QISM on the view is available through selectionModel()).

Log in to reply