def select(self, selection, flags): if isinstance(selection, QModelIndex): selection = QItemSelection(selection, selection) model = self.model() indexes = selection.indexes() sel_inds = {ind.row() for ind in indexes} | \ {ind.column() for ind in indexes} if flags == QItemSelectionModel.ClearAndSelect: selected = set() else: selected = {ind.row() for ind in self.selectedIndexes()} if flags & QItemSelectionModel.Select: selected |= sel_inds elif flags & QItemSelectionModel.Deselect: selected -= sel_inds new_selection = QItemSelection() regions = list(ranges(sorted(selected))) for r_start, r_end in regions: for c_start, c_end in regions: top_left = model.index(r_start, c_start) bottom_right = model.index(r_end - 1, c_end - 1) new_selection.select(top_left, bottom_right) QItemSelectionModel.select(self, new_selection, QItemSelectionModel.ClearAndSelect)