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)
def selectvars(varlist, command=selmodel.ClearAndSelect): indices = [data.domain.index(var) for var in varlist] itemsel = QItemSelection() for ind in indices: midx = model.index(ind) itemsel.select(midx, midx) selmodel.select(itemsel, command)
def _set_selection(self): selection = QItemSelection() index = self.tableview.model().index for row, col in self.selection: sel = index(row + 2, col + 2) selection.select(sel, sel) self.tableview.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
def _vizrank_select(self): model = self.vizrank.rank_table.model() if not model.rowCount(): return selection = QItemSelection() # This flag is needed because data in the model could be # filtered by a feature and therefore selection could not be found selection_in_model = False if self.selection: sel_names = sorted(name for name, _ in self.selection) for i in range(model.rowCount()): # pylint: disable=protected-access names = sorted(x.name for x in model.data( model.index(i, 0), CorrelationRank._AttrRole)) if names == sel_names: selection.select(model.index(i, 0), model.index(i, model.columnCount() - 1)) selection_in_model = True break if not selection_in_model: selection.select(model.index(0, 0), model.index(0, model.columnCount() - 1)) self.vizrank.rank_table.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def set_selection(self, selection): if selection: sel = QItemSelection() for row in selection: index = self.conc_view.model().index(row, 0) sel.select(index, index) self.conc_view.selectionModel().select(sel, QItemSelectionModel.SelectCurrent | QItemSelectionModel.Rows)
def select_correct(self): """Select the diagonal elements of the matrix""" selection = QItemSelection() n = self.tablemodel.rowCount() for i in range(2, n): index = self.tablemodel.index(i, i) selection.select(index, index) self.tableview.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
def selectFiltered(self): if not self.data: return itemSelection = QItemSelection() index = self.treeWidget.model().sourceModel().index mapFromSource = self.treeWidget.model().mapFromSource for i, row in enumerate(self.cells): if not self.rowFiltered(i): itemSelection.select(mapFromSource(index(i, 0)), mapFromSource(index(i, 0))) self.treeWidget.selectionModel().select(itemSelection, QItemSelectionModel.Select | QItemSelectionModel.Rows)
def select_wrong(self): """Select the off-diagonal elements of the matrix""" selection = QItemSelection() n = self.tablemodel.rowCount() for i in range(2, n): for j in range(i + 1, n): index = self.tablemodel.index(i, j) selection.select(index, index) index = self.tablemodel.index(j, i) selection.select(index, index) self.tableview.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
def __restore_selection(self): """Restore the selection on the table view from saved settings.""" selection_model = self.table_view.selectionModel() selection = QItemSelection() if len(self.selected_rows): for row in self.model.mapFromSourceRows(self.selected_rows): selection.append(QItemSelectionRange( self.model.index(row, 0), self.model.index(row, self.model.columnCount() - 1) )) selection_model.select(selection, QItemSelectionModel.ClearAndSelect)
def select(model, selection_model, selected_items): all_items = list(model) try: indices = [all_items.index(item) for item in selected_items] except: indices = [] selection = QItemSelection() for ind in indices: index = model.index(ind) selection.select(index, index) selection_model.select(selection, QItemSelectionModel.Select)
def _vizrank_select(self): model = self.vizrank.rank_table.model() selection = QItemSelection() names = sorted(x.name for x in self.selection) for i in range(model.rowCount()): # pylint: disable=protected-access if sorted(x.name for x in model.data( model.index(i, 0), CorrelationRank._AttrRole)) == names: selection.select(model.index(i, 0), model.index(i, 1)) self.vizrank.rank_table.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect) break
def update_selection(self, words): nonlocal model, proxymodel selection = QItemSelection() for i, (_, word) in enumerate(model): if word in words: index = proxymodel.mapFromSource(model.index(i, 1)) selection.select(index, index) self.__nope = True self.clearSelection() self.selectionModel().select( selection, QItemSelectionModel.Select | QItemSelectionModel.Rows) self.__nope = False
def move_rows(self, view, rows, offset): model = view.model() newrows = [min(max(0, row + offset), len(model) - 1) for row in rows] for row, newrow in sorted(zip(rows, newrows), reverse=offset > 0): model[row], model[newrow] = model[newrow], model[row] selection = QItemSelection() for nrow in newrows: index = model.index(nrow, 0) selection.select(index, index) view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def __restore_selection(self): """Restore the selection on the table view from saved settings.""" selection_model = self.table_view.selectionModel() selection = QItemSelection() # self.selected_rows can be list or numpy.array, thus # pylint: disable=len-as-condition if len(self.selected_rows): for row in self.model.mapFromSourceRows(self.selected_rows): selection.append(QItemSelectionRange( self.model.index(row, 0), self.model.index(row, self.model.columnCount() - 1) )) selection_model.select(selection, QItemSelectionModel.ClearAndSelect)
def select_rows(rows: List[int], widget: OWFeatureStatistics): """Since the widget sorts the rows, selecting rows isn't trivial.""" indices = widget.model.mapToSourceRows(rows) selection = QItemSelection() for idx in indices: selection.append(QItemSelectionRange( widget.model.index(idx, 0), widget.model.index(idx, widget.model.columnCount() - 1) )) widget.table_view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def set_selection(self): view = self.doc_list if len(self.selection): selection = QItemSelection() for row in self.selection: selection.append( QItemSelectionRange( view.model().index(row, 0), view.model().index(row, 0) ) ) view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect): """ Select rows in view. :param QAbstractItemView view: :param row_indices: Integer indices of rows to select. :param command: QItemSelectionModel.SelectionFlags """ selmodel = view.selectionModel() model = view.model() selection = QItemSelection() for row in row_indices: index = model.index(row, 0) selection.select(index, index) selmodel.select(selection, command | QItemSelectionModel.Rows)
def test_selection(self): self.send_signal("Corpus", self.corpus) widget = self.widget widget.controls.word.setText("of") view = self.widget.conc_view # Select one row, two are selected, one document on the output view.selectRow(1) self.assertEqual({ind.row() for ind in view.selectedIndexes()}, {0, 1}) self.assertEqual(self.get_output("Selected Documents"), self.corpus[[1]]) # Select a single row view.selectRow(3) self.assertEqual({ind.row() for ind in view.selectedIndexes()}, {3}) self.assertEqual(self.get_output("Selected Documents"), self.corpus[[4]]) # Add a "double" row, three are selected, two documents on the output selection_model = view.selectionModel() selection = QItemSelection() ind00 = widget.model.index(0, 0) selection.select(ind00, ind00) selection_model.select(selection, selection_model.Select) self.assertEqual({ind.row() for ind in view.selectedIndexes()}, {0, 1, 3}) self.assertEqual(self.get_output("Selected Documents"), self.corpus[[1, 4]]) # Clear selection by clicking outside ind_10 = widget.model.index(-1, 0) selection_model.select(ind_10, selection_model.Select) self.assertIsNone(self.get_output("Selected Documents")) # Selected rows emptied after word change view.selectRow(3) self.assertTrue(view.selectedIndexes()) widget.controls.word.setText("o") self.assertFalse(view.selectedIndexes())
def word_clicked(self, word): """Called from JavaScript""" if not word: self.selected_words.clear() return '' selection = QItemSelection() for i, row in enumerate(self.tablemodel): for j, val in enumerate(row): if val == word: index = self.tablemodel.index(i, j) selection.select(index, index) if word not in self.selected_words: self.selected_words.add(word) self.tableview.selectionModel().select( selection, QItemSelectionModel.Select | QItemSelectionModel.Rows) return 'selected' else: self.selected_words.remove(word) self.tableview.selectionModel().select( selection, QItemSelectionModel.Deselect | QItemSelectionModel.Rows) return ''
def set_selection(self): if len(self.selected_rows) and len(self.selected_cols): view = self.tabs.currentWidget() model = view.model() if model.rowCount() <= self.selected_rows[-1] or \ model.columnCount() <= self.selected_cols[-1]: return selection = QItemSelection() rowranges = list(ranges(self.selected_rows)) colranges = list(ranges(self.selected_cols)) for rowstart, rowend in rowranges: for colstart, colend in colranges: selection.append( QItemSelectionRange( view.model().index(rowstart, colstart), view.model().index(rowend - 1, colend - 1) ) ) view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def select(self, selection, flags): # which rows have been selected indexes = selection.indexes() if isinstance(selection, QItemSelection) \ else [selection] # prevent crashing when deleting the connection if not indexes: super().select(selection, flags) return # indexes[0].row() == -1 indicates clicking outside of the table if len(indexes) == 1 and indexes[0].row() == -1: self.clear() return word_index = self.model().word_index selected_docs = {word_index[index.row()][0] for index in indexes} selected_rows = [ row_index for row_index, (doc_index, _) in enumerate(word_index) if doc_index in selected_docs] selection = QItemSelection() # select all rows belonging to the selected document for row in selected_rows: index = self.model().index(row, 0) selection.select(index, index) super().select(selection, flags)
def commit(self, selection: QItemSelection) -> None: """Commit the selected tree to output.""" selected_indices = selection.indexes() if not len(selected_indices): self.selected_index = None self.Outputs.tree.send(None) return # We only allow selecting a single tree so there will always be one index self.selected_index = selected_indices[0].row() tree = self.rf_model.trees[self.selected_index] tree.instances = self.instances tree.meta_target_class_index = self.target_class_index tree.meta_size_calc_idx = self.size_calc_idx tree.meta_depth_limit = self.depth_limit self.Outputs.tree.send(tree)
def __cell_entered(self, model_index): if self.__clicked_cell is None: return index = self.table_model.index selection = None i_end, j_end = model_index.row(), model_index.column() i_start, j_start = self.__clicked_cell i_start, i_end = sorted([i_start, i_end]) j_start, j_end = sorted([j_start, j_end]) if i_start >= self._n_leading_rows and j_start >= self._n_leading_cols: i_start = (i_start - self._n_leading_rows) // self._n_agg_func * \ self._n_agg_func + self._n_leading_rows i_end = (i_end - self._n_leading_rows) // self._n_agg_func * \ self._n_agg_func + self._n_leading_rows + self._n_agg_func - 1 start, end = index(i_start, j_start), index(i_end, j_end) selection = QItemSelection(start, end) if selection is not None: self.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect) self.selection_changed.emit()
def test_discrete_editor_rename_selected_items_action(self): w = DiscreteVariableEditor() v = Categorical("C", ("a", "b", "c"), (("A", "1"), ("B", "b")), False) w.set_data_categorical(v, []) action = w.rename_selected_items view = w.values_edit model = view.model() selmodel = view.selectionModel() # type: QItemSelectionModel selmodel.select(QItemSelection(model.index(0, 0), model.index(1, 0)), QItemSelectionModel.ClearAndSelect) # trigger the action, then find the active popup, and simulate entry spy = QSignalSpy(w.variable_changed) with patch.object(QComboBox, "setVisible", return_value=None) as m: action.trigger() m.assert_called() cb = view.findChild(QComboBox) cb.setCurrentText("BA") view.commitData(cb) self.assertEqual(model.index(0, 0).data(Qt.EditRole), "BA") self.assertEqual(model.index(1, 0).data(Qt.EditRole), "BA") self.assertSequenceEqual(list(spy), [[]], 'variable_changed should emit exactly once')
def set_rf(self, model=None): """When a different forest is given.""" self.closeContext() self.clear() self.rf_model = model if model is not None: self.forest = self._get_forest_adapter(self.rf_model) self.forest_model[:] = self.forest.trees self.instances = model.instances self._update_info_box() self._update_target_class_combo() self._update_depth_slider() self.openContext(model) # Restore item selection if self.selected_index is not None: index = self.list_view.model().index(self.selected_index) selection = QItemSelection(index, index) self.list_view.selectionModel().select( selection, QItemSelectionModel.ClearAndSelect)
def test_discrete_editor_merge_action(self): """ This function check whether results of dialog have effect on merging the attributes. The dialog itself is tested separately. """ w = DiscreteVariableEditor() v = Categorical("C", ("a", "b", "c"), (("A", "1"), ("B", "b"))) w.set_data_categorical(v, [0, 0, 0, 1, 1, 2]) view = w.values_edit model = view.model() selmodel = view.selectionModel() # type: QItemSelectionModel selmodel.select( QItemSelection(model.index(0, 0), model.index(1, 0)), QItemSelectionModel.ClearAndSelect ) # trigger the action, then find the active popup, and simulate entry w.merge_items.trigger() self.assertEqual(model.index(0, 0).data(Qt.EditRole), "other") self.assertEqual(model.index(1, 0).data(Qt.EditRole), "other")
def test_discrete_editor_merge_action(self): w = DiscreteVariableEditor() v = Categorical("C", ("a", "b", "c"), (("A", "1"), ("B", "b"))) w.set_data(v) action = w.merge_items self.assertFalse(action.isEnabled()) view = w.values_edit model = view.model() selmodel = view.selectionModel() # type: QItemSelectionModel selmodel.select(QItemSelection(model.index(0, 0), model.index(1, 0)), QItemSelectionModel.ClearAndSelect) self.assertTrue(action.isEnabled()) # trigger the action, then find the active popup, and simulate entry spy = QSignalSpy(w.variable_changed) w.merge_items.trigger() cb = w.findChild(QComboBox) cb.setCurrentText("BA") cb.activated[str].emit("BA") cb.close() self.assertEqual(model.index(0, 0).data(Qt.EditRole), "BA") self.assertEqual(model.index(1, 0).data(Qt.EditRole), "BA") self.assertSequenceEqual(list(spy), [[]], 'variable_changed should emit exactly once')
def set_selected_items(self, inds): index = self.model().index selection = QItemSelection() for i in inds: selection.select(index(i, i), index(i, i)) self.select(selection, QItemSelectionModel.ClearAndSelect)
def autoSelection(self): selModel = self.ranksView.selectionModel() rowCount = self.ranksModel.rowCount() columnCount = self.ranksModel.columnCount() model = self.ranksProxyModel if self.selectMethod == OWRank.SelectNone: selection = QItemSelection() elif self.selectMethod == OWRank.SelectAll: selection = QItemSelection( model.index(0, 0), model.index(rowCount - 1, columnCount - 1) ) elif self.selectMethod == OWRank.SelectNBest: nSelected = min(self.nSelected, rowCount) selection = QItemSelection( model.index(0, 0), model.index(nSelected - 1, columnCount - 1) ) else: selection = QItemSelection() if len(self.selected_rows): selection = QItemSelection() for row in self.selected_rows: selection.append(QItemSelectionRange( model.index(row, 0), model.index(row, columnCount - 1))) selModel.select(selection, QItemSelectionModel.ClearAndSelect)
def test_resorting_and_selection(self): def sortby(col): model.sort(col) view.horizontalHeader().sectionClicked.emit(col) QApplication.processEvents() Names, Values, Gain = range(3) w = self.widget data = Table("heart_disease") self.send_signal(w.Inputs.data, data) self.wait_until_finished() first4 = set( sorted((var.name for var in data.domain.attributes), key=str.lower)[:4]) view = w.ranksView model = w.ranksModel selModel = view.selectionModel() columnCount = model.columnCount() w.selectionMethod = w.SelectNBest w.nSelected = 4 # Sort by gain ratio, store selection sortby(Gain) gain_sel_4 = w.selected_attrs[:] self.assertEqual(len(gain_sel_4), 4) # Sort by names or number of values: selection unchanged sortby(Values) self.assertEqual(w.selected_attrs[:], gain_sel_4) sortby(Names) self.assertEqual(w.selected_attrs[:], gain_sel_4) # Select first four (alphabetically) w.selectionMethod = w.SelectManual selection = QItemSelection(model.index(0, 0), model.index(3, columnCount - 1)) selModel.select(selection, QItemSelectionModel.ClearAndSelect) # Sanity check self.assertEqual({var.name for var in w.selected_attrs}, first4) # Manual sorting: sorting by score does not change selection sortby(Gain) self.assertEqual({var.name for var in w.selected_attrs}, first4) # Sort by first four, again sortby(Names) # Sanity check self.assertEqual({var.name for var in w.selected_attrs}, first4) w.selectionMethod = w.SelectNBest # Sanity check self.assertEqual({var.name for var in w.selected_attrs}, first4) # Sorting by gain must change selection sortby(Gain) self.assertEqual(set(w.selected_attrs), set(gain_sel_4))
def _select_rows(self): model = self.view.model() n_rows, n_columns = model.rowCount(), model.columnCount() if self.sel_method == SelectionMethods.NONE: selection = QItemSelection() elif self.sel_method == SelectionMethods.ALL: selection = QItemSelection(model.index(0, 0), model.index(n_rows - 1, n_columns - 1)) elif self.sel_method == SelectionMethods.MANUAL: selection = QItemSelection() for i in range(n_rows): word = model.data(model.index(i, 0)) if word in self.selected_words: _selection = QItemSelection(model.index(i, 0), model.index(i, n_columns - 1)) selection.merge(_selection, QItemSelectionModel.Select) elif self.sel_method == SelectionMethods.N_BEST: n_sel = min(self.n_selected, n_rows) selection = QItemSelection(model.index(0, 0), model.index(n_sel - 1, n_columns - 1)) else: raise NotImplementedError self.view.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
def select(self, selection, flags): """Reimplemented.""" if isinstance(selection, QModelIndex): selection = QItemSelection(selection, selection) if not self.__selectBlocks: super().select(selection, flags) return model = self.model() def to_ranges(spans): return list(range(*r) for r in spans) if flags & QItemSelectionModel.Current: # no current selection support flags &= ~QItemSelectionModel.Current if flags & QItemSelectionModel.Toggle: # no toggle support either flags &= ~QItemSelectionModel.Toggle flags |= QItemSelectionModel.Select if flags == QItemSelectionModel.ClearAndSelect: # extend selection ranges in `selection` to span all row/columns sel_rows = selection_rows(selection) sel_cols = selection_columns(selection) selection = QItemSelection() for row_range, col_range in \ itertools.product(to_ranges(sel_rows), to_ranges(sel_cols)): selection.select( model.index(row_range.start, col_range.start), model.index(row_range.stop - 1, col_range.stop - 1) ) elif flags & (QItemSelectionModel.Select | QItemSelectionModel.Deselect): # extend all selection ranges in `selection` with the full current # row/col spans rows, cols = selection_blocks(self.selection()) sel_rows = selection_rows(selection) sel_cols = selection_columns(selection) ext_selection = QItemSelection() for row_range, col_range in \ itertools.product(to_ranges(rows), to_ranges(sel_cols)): ext_selection.select( model.index(row_range.start, col_range.start), model.index(row_range.stop - 1, col_range.stop - 1) ) for row_range, col_range in \ itertools.product(to_ranges(sel_rows), to_ranges(cols)): ext_selection.select( model.index(row_range.start, col_range.start), model.index(row_range.stop - 1, col_range.stop - 1) ) selection.merge(ext_selection, QItemSelectionModel.Select) super().select(selection, flags)
def select(self, selection, flags): """Reimplemented.""" if isinstance(selection, QModelIndex): selection = QItemSelection(selection, selection) model = self.model() indexes = self.selectedIndexes() rows = set(ind.row() for ind in indexes) cols = set(ind.column() for ind in indexes) if flags & QItemSelectionModel.Select and \ not flags & QItemSelectionModel.Clear and self.__selectBlocks: indexes = selection.indexes() sel_rows = set(ind.row() for ind in indexes).union(rows) sel_cols = set(ind.column() for ind in indexes).union(cols) selection = QItemSelection() for r_start, r_end in ranges(sorted(sel_rows)): for c_start, c_end in ranges(sorted(sel_cols)): top_left = model.index(r_start, c_start) bottom_right = model.index(r_end - 1, c_end - 1) selection.select(top_left, bottom_right) elif self.__selectBlocks and flags & QItemSelectionModel.Deselect: indexes = selection.indexes() def to_ranges(indices): return list(range(*r) for r in ranges(indices)) selected_rows = to_ranges(sorted(rows)) selected_cols = to_ranges(sorted(cols)) desel_rows = to_ranges(set(ind.row() for ind in indexes)) desel_cols = to_ranges(set(ind.column() for ind in indexes)) selection = QItemSelection() # deselection extended vertically for row_range, col_range in \ itertools.product(selected_rows, desel_cols): selection.select( model.index(row_range.start, col_range.start), model.index(row_range.stop - 1, col_range.stop - 1) ) # deselection extended horizontally for row_range, col_range in \ itertools.product(desel_rows, selected_cols): selection.select( model.index(row_range.start, col_range.start), model.index(row_range.stop - 1, col_range.stop - 1) ) QItemSelectionModel.select(self, selection, flags)
def _set_selected_words(self, indices: List[int]): selection = QItemSelection() sel_model: QItemSelectionModel = self.words_view.selectionModel() for i in indices: selection.append(QItemSelectionRange(self.words_model.index(i, 0))) sel_model.select(selection, QItemSelectionModel.ClearAndSelect)
def select_tree(self, idx: int) -> None: list_view = self.widget.list_view index = list_view.model().index(idx) selection = QItemSelection(index, index) list_view.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
def itsel(self, rows): sel = QItemSelection() for row in rows: index = self.store.proxy.index(row, 0) sel.select(index, index) return sel
def qitemselection_select_range(selection: QItemSelection, model: QAbstractItemModel, rows: range, columns: range) -> None: assert rows.step == 1 and columns.step == 1 selection.select(model.index(rows.start, columns.start), model.index(rows.stop - 1, columns.stop - 1))
def _select_rows(self): proxy_model = self.view.model() n_rows, n_columns = proxy_model.rowCount(), proxy_model.columnCount() if self.sel_method == SelectionMethods.NONE: selection = QItemSelection() elif self.sel_method == SelectionMethods.ALL: selection = QItemSelection( proxy_model.index(0, 0), proxy_model.index(n_rows - 1, n_columns - 1)) elif self.sel_method == SelectionMethods.MANUAL: selection = QItemSelection() new_sel = [] for row in self.selected_rows: if row < n_rows: new_sel.append(row) _selection = QItemSelection( self.model.index(row, 0), self.model.index(row, n_columns - 1)) selection.merge( proxy_model.mapSelectionFromSource(_selection), QItemSelectionModel.Select, ) # selected rows must be updated when the same dataset with less rows # appear at the input - it is not handled by selectionChanged # in cases when all selected rows missing in new table self.selected_rows = new_sel elif self.sel_method == SelectionMethods.N_BEST: n_sel = min(self.n_selected, n_rows) selection = QItemSelection( proxy_model.index(0, 0), proxy_model.index(n_sel - 1, n_columns - 1)) else: raise NotImplementedError self.view.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)