def accepted(): try: shift, n = intintinput_dialog.sbOffset.value( ), intintinput_dialog.sbn.value() shift = shift % n i = 0 self.selecting = True flags = QItemSelectionModel.Select selection = QItemSelection() for item in self.myModel.iterate_selected_items( skip_groups=True, skip_childs_in_selected_groups=False, clear_selection=True): if i % n == shift: start_index = self.myModel.createIndex( item.row(), 0, item) end_index = self.myModel.createIndex( item.row(), 1, item) selection.select(start_index, end_index) i += 1 self.selectionModel().select(selection, flags) except Exception as ex: Logger.message(ex.__str__()) QMessageBox.warning(self, 'Error', ex.__str__(), QMessageBox.Ok) finally: self.selecting = False
def selectionChanged(self, selected, deselected): super(TreeView, self).selectionChanged(selected, deselected) if self.selecting or self.deleting: return self.selecting = True # select all children if group was selected for item in self.myModel.iterate_selected_items( skip_groups=False, skip_childs_in_selected_groups=True): # help from https://stackoverflow.com/questions/47271494/set-selection-from-a-list-of-indexes-in-a-qtreeview if isinstance(item, SpectrumItemGroup): # mod = self.model() # columns = mod.columnCount() - 1 length = item.__len__() if length == 0: continue flags = QItemSelectionModel.Select selection = QItemSelection() start_index = self.myModel.createIndex(0, 0, item.children[0]) end_index = self.myModel.createIndex(length - 1, 1, item.children[-1]) selection.select(start_index, end_index) self.selectionModel().select(selection, flags) self.selecting = False
def select(self, selection, command): """Extend behavior of inherited method. Add all sub items to selection """ # if the selection is a QModelIndex return und don do anything if isinstance(selection, QModelIndex): if not selection.isValid(): self.clearSelection() return indexes_selected = [selection] # If the selection is an index, a range only containing this index # has to be created recursive_selection = QItemSelection() q_index_parent = self.model().parent(selection) q_index_first = selection q_index_last = self.model().index(selection.row(), selection.column(), q_index_parent) recursive_selection.select(q_index_first, q_index_last) # Handle selections and single indexes if isinstance(selection, QItemSelection): indexes_selected = selection.indexes() recursive_selection = selection # Find index ranges of all sub items of the indexes in `selection` index_ranges = self._get_sub_items_index_ranges(indexes_selected) # Add the index ranges to the `selection` for (q_index_1, q_index_2) in index_ranges: # TODO Problem could be, that select leads to duplicates in the # selection. So far, no problem arose. `merge` is no alternative # as it does not support all `commands` recursive_selection.select(q_index_1, q_index_2) super().select(recursive_selection, command)
def select(self, uuids, lbox: QTreeView = None, scroll_to_show_single=True): lbox = self.current_set_listbox if lbox is None else lbox lbox.clearSelection() if not uuids: return # FUTURE: this is quick and dirty rowdict = dict( (u, i) for i, u in enumerate(self.doc.current_layer_uuid_order)) items = QItemSelection() q = None for uuid in uuids: row = rowdict.get(uuid, None) if row is None: LOG.error( 'UUID {} cannot be selected in list view'.format(uuid)) continue q = self.createIndex(row, 0) items.select(q, q) lbox.selectionModel().select(items, QItemSelectionModel.Select) # lbox.setCurrentIndex(q) if scroll_to_show_single and len(uuids) == 1 and q is not None: lbox.scrollTo(q)
def _set_selection(self, row_list): selection = QItemSelection() model = self.table.model() for row in row_list: index = model.index(row, 0) selection.select(index, index) self.table.selectionModel().select(selection, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Current)
def _restoreSelection(self): newSelection = QItemSelection() for index in self.model.selected_indexes: newSelection.select(self.createIndex(index, 0), self.createIndex(index, 0)) self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect) if len(newSelection.indexes()): currentIndex = newSelection.indexes()[0] self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current) self.view.scrollTo(currentIndex)
def _set_selection(self, row_list): selection = QItemSelection() model = self.table.model() for row in row_list: if self._reverse_order: row = len(self._config_dictionaries) - row - 1 index = model.index(row, 0) selection.select(index, index) self.table.selectionModel().select(selection, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Current)
def _updateViewSelection(self): # Takes the selection on the model's side and update the view with it. newSelection = QItemSelection() columnCount = self.columnCount(QModelIndex()) for index in self.model.selected_indexes: newSelection.select(self.createIndex(index, 0), self.createIndex(index, columnCount-1)) self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect) if len(newSelection.indexes()): currentIndex = newSelection.indexes()[0] self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current) self.view.scrollTo(currentIndex)
def _set_selection(self, row_list): selection = QItemSelection() model = self.table.model() for row in row_list: if self._reverse_order: row = len(self._config_dictionaries) - row - 1 index = model.index(row, 0) selection.select(index, index) self.table.selectionModel().select( selection, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Current)
def on_btnCheckAll_clicked(self): sel = self.tableView.selectionModel() # block_old = sel.blockSignals(True) sel_modified = False s = QItemSelection() for row_idx, utxo in enumerate(self.utxos): index = self.table_model.index(row_idx, 0) if not utxo['coinbase_locked'] and not utxo.get('spent_date'): if not sel.isSelected(index): sel_modified = True s.select(index, index) if sel_modified: sel.select(s, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
def handle_submit(self): """Handle submit button click. On submit button click, we try to push the finish times for the selected rows to the corresponding racer. For each selection that succeeds, we remove that row from this table. """ race_table_model = self.modeldb.race_table_model selection_list = self.selectionModel().selectedRows() # Remove rows from large to small, because the rows are removed # immediately, and cause the rest of the rows to shift, invalidating # any row number that's higher than the currently removed one. selection_list.sort(key=lambda selection: selection.row(), reverse=True) deleted_selection = QItemSelection() for selection in selection_list: try: # Only try to submit it if it's a non-negative integer. # Else, it is obviously a work in progress, so don't even # bother. record = self.source_model.record(selection.row()) scratchpad = record.value(ResultTableModel.SCRATCHPAD) if scratchpad.isdigit(): self.source_model.submit_result(selection.row()) deleted_selection.select(selection, selection) reference_datetime = race_table_model.get_reference_clock_datetime( ) bib = record.value(ResultTableModel.SCRATCHPAD) msecs = record.value(ResultTableModel.FINISH) finish = reference_datetime.addMSecs(msecs).toString( defaults.DATETIME_FORMAT) self.journal.log( 'Result with bib "%s" and time "%s" submitted.' % (bib, finish)) except InputError as e: QMessageBox.warning(self, 'Error', str(e)) # Model retains blank rows until we select() again. self.source_model.select() # Surprisingly, when the model changes such that our selection changes # (for example, when the selected result gets submitted to the racer # table model and gets deleted from the result table model), the # selectionChanged signal is NOT emitted. So, we have to emit that # ourselves here. self.selectionModel().selectionChanged.emit(QItemSelection(), deleted_selection)
def selectTilesInStamp(self, stamp): if self.mEmittingStampCaptured: return processed = QSet() selections = QMap() for variation in stamp.variations(): tileLayer = variation.tileLayer() for cell in tileLayer: tile = cell.tile if tile: if (processed.contains(tile)): continue processed.insert(tile) # avoid spending time on duplicates tileset = tile.tileset() tilesetIndex = self.mTilesets.indexOf( tileset.sharedPointer()) if (tilesetIndex != -1): view = self.tilesetViewAt(tilesetIndex) if (not view.model()): # Lazily set up the model self.setupTilesetModel(view, tileset) model = view.tilesetModel() modelIndex = model.tileIndex(tile) selectionModel = view.selectionModel() _x = QItemSelection() _x.select(modelIndex, modelIndex) selections[selectionModel] = _x if (not selections.isEmpty()): self.mSynchronizingSelection = True # Mark captured tiles as selected for i in selections: selectionModel = i[0] selection = i[1] selectionModel.select(selection, QItemSelectionModel.SelectCurrent) # Show/edit properties of all captured tiles self.mMapDocument.setSelectedTiles(processed.toList()) # Update the current tile (useful for animation and collision editors) first = selections.first() selectionModel = first[0] selection = first[1] currentIndex = QModelIndex(selection.first().topLeft()) if (selectionModel.currentIndex() != currentIndex): selectionModel.setCurrentIndex(currentIndex, QItemSelectionModel.NoUpdate) else: self.currentChanged(currentIndex) self.mSynchronizingSelection = False
def __restoreSelection(self): # Restore previous selection for root (if available) assert self.__model is not None groupind = self.__currentIndex root = self.__model.index(groupind, 0) sel = self.__selections.get(groupind, []) indices = [ self.__model.index(pind.row(), pind.column(), root) for pind in sel if pind.isValid() and pind.parent() == root ] selection = QItemSelection() for ind in indices: selection.select(ind, ind) self.values_view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def selection(self): """ Return the item selection. Returns ------- selection : QtCore.QItemSelection """ selection = QItemSelection() if self.__model is None: return selection for pind in chain(*self.__selections.values()): ind = self.__model.index(pind.row(), pind.column(), pind.parent()) if ind.isValid(): selection.select(ind, ind) return selection
def itemselection(modelindexlist): """ Return an QtCore.QItemSelection from QModelIndex list Parameters ---------- modelindexlist : list of QtCore.QModelIndex Selected model indices. Returns ------- selection : QtCore.QItemSelection """ selection = QItemSelection() for index in modelindexlist: selection.select(index, index) return selection
def _sync_api_selection_to_grid(self, rows: list[int], changed: bool) -> None: if not self.model(): return if self._collect_rows() == self._api.subs.selected_indexes: return self.setUpdatesEnabled(False) self.selectionModel().selectionChanged.disconnect( self._sync_grid_selection_to_api) selection = QItemSelection() for row in self._api.subs.selected_indexes: idx = self.model().index(row, 0) selection.select(idx, idx) self.selectionModel().clear() if self._api.subs.selected_indexes: first_row = self._api.subs.selected_indexes[0] cell_index = self.model().index(first_row, 0) self.setCurrentIndex(cell_index) self.scrollTo(cell_index) self.selectionModel().select( selection, QItemSelectionModel.SelectionFlag( QItemSelectionModel.SelectionFlag.Rows | QItemSelectionModel.SelectionFlag.Current | QItemSelectionModel.SelectionFlag.Select), ) self.selectionModel().selectionChanged.connect( self._sync_grid_selection_to_api) self.setUpdatesEnabled(True)
def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Delete: selected = self.selectionModel().selection() """:type: QtGui.QItemSelection """ if selected.isEmpty(): return min_row = numpy.min([rng.top() for rng in selected]) max_row = numpy.max([rng.bottom() for rng in selected]) start = numpy.min([rng.left() for rng in selected]) end = numpy.max([rng.right() for rng in selected]) self.setEnabled(False) self.setCursor(Qt.WaitCursor) self.model().delete_range(min_row, max_row, start, end) self.unsetCursor() self.setEnabled(True) self.setFocus() if event.matches(QKeySequence.Copy): cells = self.selectedIndexes() cells.sort() currentRow = 0 text = "" for cell in cells: if len(text) > 0 and cell.row() != currentRow: text += "\n" currentRow = cell.row() if cell.data(): text += str(cell.data()) QApplication.instance().clipboard().setText(text) return if event.key() not in (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down) \ or event.modifiers() == Qt.ShiftModifier: super().keyPressEvent(event) return sel = self.selectionModel().selectedIndexes() cols = [i.column() for i in sel] rows = [i.row() for i in sel] if len(cols) == 0 or len(rows) == 0: super().keyPressEvent(event) return mincol, maxcol = numpy.min(cols), numpy.max(cols) minrow, maxrow = numpy.min(rows), numpy.max(rows) scroll_to_start = True if event.key() == Qt.Key_Right and maxcol < self.model().col_count - 1: maxcol += 1 mincol += 1 scroll_to_start = False elif event.key() == Qt.Key_Left and mincol > 0: mincol -= 1 maxcol -= 1 elif event.key( ) == Qt.Key_Down and maxrow < self.model().row_count - 1: first_unhidden = -1 for row in range(maxrow + 1, self.model().row_count): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = maxrow - minrow maxrow = first_unhidden minrow = maxrow - sel_len scroll_to_start = False elif event.key() == Qt.Key_Up and minrow > 0: first_unhidden = -1 for row in range(minrow - 1, -1, -1): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = maxrow - minrow minrow = first_unhidden maxrow = minrow + sel_len start = self.model().index(minrow, mincol) end = self.model().index(maxrow, maxcol) selctn = QItemSelection() selctn.select(start, end) self.selectionModel().setCurrentIndex( end, QItemSelectionModel.ClearAndSelect) self.selectionModel().select(selctn, QItemSelectionModel.ClearAndSelect) if scroll_to_start: self.scrollTo(start) else: self.scrollTo(end)
def select(self, row_1, col_1, row_2, col_2): selection = QItemSelection() start_index = self.model().index(row_1, col_1) end_index = self.model().index(row_2, col_2) selection.select(start_index, end_index) self.selectionModel().select(selection, QItemSelectionModel.Select)
def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Delete: min_row, max_row, start, end = self.selection_range() if min_row == max_row == start == end == -1: return self.setEnabled(False) self.setCursor(Qt.WaitCursor) self.model().delete_range(min_row, max_row, start, end - 1) self.unsetCursor() self.setEnabled(True) self.setFocus() if event.matches(QKeySequence.Copy): self.on_copy_action_triggered() return if event.key() == Qt.Key_Space: min_row, max_row, start, _ = self.selection_range() if start == -1: return self.model().insert_column(start, list(range(min_row, max_row + 1))) if event.key() not in (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down) \ or event.modifiers() == Qt.ShiftModifier: super().keyPressEvent(event) return min_row, max_row, min_col, max_col = self.selection_range() if min_row == max_row == min_col == max_col == -1: super().keyPressEvent(event) return max_col -= 1 scroll_to_start = True if event.key() == Qt.Key_Right and max_col < self.model().col_count - 1: max_col += 1 min_col += 1 scroll_to_start = False elif event.key() == Qt.Key_Left and min_col > 0: min_col -= 1 max_col -= 1 elif event.key() == Qt.Key_Down and max_row < self.model().row_count - 1: first_unhidden = -1 for row in range(max_row + 1, self.model().row_count): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = max_row - min_row max_row = first_unhidden min_row = max_row - sel_len scroll_to_start = False elif event.key() == Qt.Key_Up and min_row > 0: first_unhidden = -1 for row in range(min_row - 1, -1, -1): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = max_row - min_row min_row = first_unhidden max_row = min_row + sel_len start = self.model().index(min_row, min_col) end = self.model().index(max_row, max_col) selection = QItemSelection() selection.select(start, end) self.setCurrentIndex(start) self.selectionModel().setCurrentIndex(end, QItemSelectionModel.ClearAndSelect) self.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect) if scroll_to_start: self.scrollTo(start) else: self.scrollTo(end)
def keyPressEvent(self, event: QKeyEvent): if event.key() == Qt.Key_Delete: min_row, max_row, start, end = self.selection_range() if min_row == max_row == start == end == -1: return self.setEnabled(False) self.setCursor(Qt.WaitCursor) self.model().delete_range(min_row, max_row, start, end - 1) self.unsetCursor() self.setEnabled(True) self.setFocus() if event.matches(QKeySequence.Copy): self.on_copy_action_triggered() return if event.key() == Qt.Key_Space: min_row, max_row, start, _ = self.selection_range() if start == -1: return self.model().insert_column(start, list(range(min_row, max_row + 1))) if event.key() not in (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down) \ or event.modifiers() == Qt.ShiftModifier: super().keyPressEvent(event) return min_row, max_row, min_col, max_col = self.selection_range() if min_row == max_row == min_col == max_col == -1: super().keyPressEvent(event) return max_col -= 1 scroll_to_start = True if event.key( ) == Qt.Key_Right and max_col < self.model().col_count - 1: max_col += 1 min_col += 1 scroll_to_start = False elif event.key() == Qt.Key_Left and min_col > 0: min_col -= 1 max_col -= 1 elif event.key( ) == Qt.Key_Down and max_row < self.model().row_count - 1: first_unhidden = -1 for row in range(max_row + 1, self.model().row_count): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = max_row - min_row max_row = first_unhidden min_row = max_row - sel_len scroll_to_start = False elif event.key() == Qt.Key_Up and min_row > 0: first_unhidden = -1 for row in range(min_row - 1, -1, -1): if not self.isRowHidden(row): first_unhidden = row break if first_unhidden != -1: sel_len = max_row - min_row min_row = first_unhidden max_row = min_row + sel_len start = self.model().index(min_row, min_col) end = self.model().index(max_row, max_col) selection = QItemSelection() selection.select(start, end) self.setCurrentIndex(start) self.selectionModel().setCurrentIndex( end, QItemSelectionModel.ClearAndSelect) self.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect) if scroll_to_start: self.scrollTo(start) else: self.scrollTo(end)
def __init__(self, controls, parent=None, status=None): QDialog.__init__(self, parent) self.setWindowTitle("puddletag settings") winsettings('settingswin', self) built_in = [ (translate("Settings", 'General'), GeneralSettings(controls), controls), (translate("Settings", 'Confirmations'), confirmations.Settings(), None), (translate("Settings", 'Mappings'), TagMappings(), None), (translate("Settings", 'Playlist'), Playlist(), None), (translate("Settings", 'Colours'), ColorEdit(), status['table']), (translate("Settings", 'Genres'), genres.Genres(status=status), None), (translate("Settings", 'Tags'), Tags(status=status), status['table']), (translate("Settings", 'Plugins'), PluginConfig(), None), (translate("Settings", 'Shortcuts'), ActionEditorDialog(status['actions']), None), ] d = dict(enumerate(built_in)) i = len(d) for control in controls: if hasattr(control, SETTINGSWIN): c = getattr(control, SETTINGSWIN)(status=status) d[i] = [c.title, c, control] i += 1 for c in config_widgets: d[i] = [c.title, c(status=status), None] i += 1 self._widgets = d self.listbox = SettingsList() self.model = ListModel(d) self.listbox.setModel(self.model) self.stack = QStackedWidget() self.stack.setFrameStyle(QFrame.StyledPanel) self.grid = QGridLayout() self.grid.addWidget(self.listbox) self.grid.addWidget(self.stack, 0, 1) self.grid.setColumnStretch(1, 2) self.setLayout(self.grid) self.listbox.selectionChangedSignal.connect(self.showOption) selection = QItemSelection() self.selectionModel = QItemSelectionModel(self.model) index = self.model.index(0, 0) selection.select(index, index) self.listbox.setSelectionModel(self.selectionModel) self.selectionModel.select(selection, QItemSelectionModel.Select) self.okbuttons = OKCancel() self.okbuttons.okButton.setDefault(True) self.grid.addLayout(self.okbuttons, 1, 0, 1, 2) self.okbuttons.ok.connect(self.saveSettings) self.accepted.connect(self.saveSettings) self.okbuttons.cancel.connect(self.close)