Is it possible to deselect in a QTreeView by clicking off an item?

后端 未结 8 1174
盖世英雄少女心
盖世英雄少女心 2020-12-30 05:35

I\'d like to be able to deselect items in my QTreeView by clicking in a part of the QTreeView with no items in, but I can\'t seem to find anyway of doing this. I\'d intercep

相关标签:
8条回答
  • 2020-12-30 06:30

    In the answer by @Skilldrick, we risk sending superfluous events. If an item is already selected, and we're clicking it again, we are raising deselected and selected events. Based on other listeners in your application, this might not be what you want.

    The solution by @eric-maeker only deselects an item if we click it again while it is already selected. Strictly speaking, this is not the answer to the original question, which was how to deselect the selected item when clicking somewhere else.

    @yassir-ennazk gets close, but as pointed out by @adrian-maire, the solution is not optimal. event->pos() is evaluated twice. Also, the mouse event is always evaluated by calling QTreeView::mousePressEvent.

    Here's the solution I've come up with, based on the other answers mentioned above. If we're clicking at a point where another tree view item is present, the new item is selected by forwarding the event to the TreeView. If not, we're clearing the selection.

    Note that this works for QTreeWidgets as well.

    virtual void mousePressEvent(QMouseEvent* event)
    {
        QModelIndex item = indexAt(event->pos());
    
        if (item.isValid())
        {
            QTreeView::mousePressEvent(event);
        }
        else
        {
            clearSelection();
            const QModelIndex index;
            selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select);
        }
    }
    
    0 讨论(0)
  • 2020-12-30 06:31

    You could try setting a different selection mode for your widget. I don't know if any of them quite covers what it appears you want (single selection, but deselectable).

    0 讨论(0)
提交回复
热议问题