from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class CustomTreeView(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.selectionModel().selectionChanged.connect(self.on_selection_changed)
def mousePressEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
index = self.indexAt(event.pos())
self.selectionModel().select(index, QItemSelectionModel.Rows | QItemSelectionModel.Deselect)
else:
super().mousePressEvent(event)
def mouseReleaseEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton and QApplication.keyboardModifiers() != Qt.ShiftModifier:
super().mouseReleaseEvent(event)
def on_selection_changed(self):
selected_indexes = self.selectionModel().selectedIndexes()
for index in self.selectedIndexes():
if index not in selected_indexes:
self.selectionModel().select(index, QItemSelectionModel.Rows | QItemSelectionModel.Deselect)
from PyQt4.QtGui import *
class CustomTreeView(QTreeView):
def __init__(self, parent=None):
super(CustomTreeView, self).__init__(parent)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.selectionModel().selectionChanged.connect(self.on_selection_changed)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
modifiers = QApplication.keyboardModifiers()
if modifiers == Qt.ShiftModifier:
index = self.indexAt(event.pos())
self.selectionModel().select(index, QItemSelectionModel.Rows | QItemSelectionModel.Deselect)
else:
super(CustomTreeView, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and QApplication.keyboardModifiers() != Qt.ShiftModifier:
super(CustomTreeView, self).mouseReleaseEvent(event)
def on_selection_changed(self):
selected_indexes = self.selectionModel().selectedIndexes()
for index in self.selectedIndexes():
if index not in selected_indexes:
self.selectionModel().select(index, QItemSelectionModel.Rows | QItemSelectionModel.Deselect)