python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class CustomTreeView(QTreeView):
def __init__(self, parent=None):
super(CustomTreeView, self).__init__(parent)
self.ctrl_pressed = False
self.shift_pressed = False
self.select_children = True
self.shift_begin_index = None
def keyPressEvent(self, event):
if event.key() == Qt.Key_Control:
self.ctrl_pressed = True
elif event.key() == Qt.Key_Shift:
self.shift_pressed = True
else:
super(CustomTreeView, self).keyPressEvent(event)
def keyReleaseEvent(self, event):
if event.key() == Qt.Key_Control:
self.ctrl_pressed = False
elif event.key() == Qt.Key_Shift:
self.shift_pressed = False
self.shift_begin_index = None
else:
super(CustomTreeView, self).keyReleaseEvent(event)
def get_children_indexes(self, index):
children_indexes = []
stack = [index]
while stack:
parent_index = stack.pop()
for row in range(self.model().rowCount(parent_index)):
child_index = self.model().index(row, 0, parent_index)
stack.append(child_index)
children_indexes.append(child_index)
return children_indexes
def mousePressEvent(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return
if self.ctrl_pressed:
# Ctrl按下,切换当前项的选择状态
current_selected = self.selectionModel().isSelected(index)
self.selectionModel().select(index, QItemSelectionModel.Select if not current_selected else QItemSelectionModel.Deselect)
if self.select_children:
children_indexes = self.get_children_indexes(index)
for child_index in children_indexes:
self.selectionModel().select(child_index, QItemSelectionModel.Select if not current_selected else QItemSelectionModel.Deselect)
elif self.shift_pressed:
currentIndexes = self.selectionModel().currentIndex()
if self.shift_begin_index is None:
self.shift_begin_index = currentIndexes
prev_selected_index = self.shift_begin_index if self.shift_begin_index else currentIndexes
if prev_selected_index.isValid():
# 清除先前的选择区域
top_left_index = index if index.row() < prev_selected_index.row() else prev_selected_index
bottom_right_index = index if index.row() >= prev_selected_index.row() else prev_selected_index
prev_area = QItemSelection(top_left_index, bottom_right_index)
self.selectionModel().select(prev_area, QItemSelectionModel.Deselect)
# 重新计算范围,包括子节点
selection = QItemSelection(prev_selected_index, index)
self.selectionModel().select(selection, QItemSelectionModel.Select)
for i in range(selection.count()):
for index in selection.at(i).indexes():
children_indexes = self.get_children_indexes(index)
for child_index in children_indexes:
self.selectionModel().select(child_index, QItemSelectionModel.Select)
else:
# 没有按下Ctrl或Shift,执行默认的点击选中逻辑
super(CustomTreeView, self).mousePressEvent(event)
def main():
app = QApplication(sys.argv)
model = QDirModel()
tree_view = CustomTreeView()
tree_view.setModel(model)
tree_view.setRootIndex(model.index(QDir.homePath()))
tree_view.setSelectionMode(QAbstractItemView.ExtendedSelection)
tree_view.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()