Reputation: 1103
Is there any way to use the QAbstractItemView::MultiSelection
so the selection is not cleared when selecting another item (so no need to use ctrl to continue selecting), and allow to keep selecting items by click+dragging up and down (done by default when setting the selection mode to MultiSelection), but also to select items with the shift effect as done when setting the selection mode to QAbstractItemView::ExtendedSelection
?
Upvotes: 1
Views: 52
Reputation: 48444
The simplest solution may be to override QAbstractItemView::selectionCommand()
, which is normally called by item views whenever a user event may cause a (possibly complex) selection change.
The concept is relatively simple: override selectionCommand()
and, whenever it's triggered by a keyboard or mouse event that uses a Qt::ShiftModifier
, temporarily switch to the ExtendedSelection
mode, then call the base implementation of the class and keep its result, restore the original selection mode and return the result above.
I am not able to provide C++ compliant code, but the simplicity of the following PyQt/PySide example should be enough to demonstrate the concept.
class ComplexSelectionTreeWidget(QTreeWidget):
def selectionCommand(self, index, event=None):
if (
isinstance(event, QInputEvent)
and event.modifiers() == Qt.ShiftModifier
):
orig = self.selectionMode()
self.setSelectionMode(self.ExtendedSelection)
res = super().selectionCommand(index, event)
self.setSelectionMode(orig)
return res
return super().selectionCommand(index, event)
Here I subclassed QTreeWidget, but it would work similarly for any standard Qt item view (including the inherited QTreeView), except maybe for QColumnView, since it's based on multiple QListViews..
The result of the above is that whenever the Shift key is pressed for input events it will temporarily switch to the extended mode, allowing shift-selection including items selected with the keyboard or the mouse.
Note that the default behavior of that mode is to always extend the selection based on the current index of the view, which may become slightly unintuitive when other items are being selected in the MultiSelection
.
A previous answer probably addressed that (I didn't test it though), but unfortunately it was deleted by their author. You may check it if you've enough reputation (>=10k).
Upvotes: 0