Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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:

    "http://stackoverflow.com/questions/2761284/is-it-possible-to-deselect-in-a-qtreeview-by-clicking-off-an-item
    ":http://stackoverflow.com/questions/2761284/is-it-possible-to-deselect-in-a-qtreeview-by-clicking-off-an-item

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

    @
    void DeselectableTreeView::mousePressEvent(QMouseEvent* event)
    {
    this->clearSelection();
    QTreeView::mousePressEvent(event);

    if(!this->selectedIndexes().count())
    {
    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 {
    clearSelection();
    }
    @

    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