def on_selectionChanged(self): """ Runs when cells are selected in the Header. This selects columns in the data table when the header is clicked, and then calls selectAbove() """ # Check focus so we don't get recursive loop, since headers trigger selection of data cells and vice versa if self.hasFocus(): dataView = self.parent().dataView # Set selection mode so selecting one row or column at a time adds to selection each time if ( self.orientation == Qt.Horizontal ): # This case is for the horizontal header # Get the header's selected columns selection = self.selectionModel().selection() # Removes the higher levels so that only the lowest level of the header affects the data table selection last_row_ix = self.pgdf.dataframe.columns.nlevels - 1 last_col_ix = self.model().columnCount() - 1 higher_levels = QtCore.QItemSelection( self.model().index(0, 0), self.model().index(last_row_ix - 1, last_col_ix), ) selection.merge(higher_levels, QtCore.QItemSelectionModel.Deselect) # Select the cells in the data view dataView.selectionModel().select( selection, QtCore.QItemSelectionModel.Columns | QtCore.QItemSelectionModel.ClearAndSelect, ) if self.orientation == Qt.Vertical: selection = self.selectionModel().selection() last_row_ix = self.model().rowCount() - 1 last_col_ix = self.pgdf.dataframe.index.nlevels - 1 higher_levels = QtCore.QItemSelection( self.model().index(0, 0), self.model().index(last_row_ix, last_col_ix - 1), ) selection.merge(higher_levels, QtCore.QItemSelectionModel.Deselect) dataView.selectionModel().select( selection, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.ClearAndSelect, ) self.selectAbove()
def select(self, selection, command): ''' overwrite the select function selection is either a QModelIndex, (handled normally), or a QItemSelection ''' if isinstance(selection, QtCore.QModelIndex): QtCore.QItemSelectionModel.select(self, selection, command) return if len(selection.indexes()) > 2: LOGGER.debug("restricting appointment selection to 2 items") new_selection = QtCore.QItemSelection() new_selection.append( QtCore.QItemSelectionRange(selection.indexes()[0])) new_selection.append( QtCore.QItemSelectionRange(selection.last().indexes()[0])) selection = new_selection # now some openmolar specific code... I want scheduled appointment # to take priority if len(selection.indexes()) == 2: index1, index2 = selection.indexes() app1 = index1.model().data(index1, QtCore.Qt.UserRole) app2 = index2.model().data(index2, QtCore.Qt.UserRole) swap_required = app1.unscheduled and not app2.unscheduled LOGGER.debug("swap required = %s", swap_required) if swap_required: selection.swap(0, 1) if app1.dent == app2.dent: # joint appointments are dumb if dentist is the same! selection.removeAt(1) # send via base class QtCore.QItemSelectionModel.select(self, selection, command)
def _sync_api_selection_to_grid(self, rows: T.List[int], changed: bool) -> None: if self._collect_rows() == self._api.subs.selected_indexes: return self.setUpdatesEnabled(False) self.selectionModel().selectionChanged.disconnect( self._sync_grid_selection_to_api) selection = QtCore.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, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.Current | QtCore.QItemSelectionModel.Select, ) self.selectionModel().selectionChanged.connect( self._sync_grid_selection_to_api) self.setUpdatesEnabled(True)
def select(self, selection, command): ''' overwrite the select function selection is either a QModelIndex, (handled normally), or a QItemSelection ''' self.is_reversed = False LOGGER.debug("DoubleRowSelectionModel.select %s,%s", selection, command) if isinstance(selection, QtCore.QModelIndex): LOGGER.debug("Model Index selected") elif len(selection.indexes()) >= 2: LOGGER.debug("restricting appointment selection to 2 items") new_selection = QtCore.QItemSelection() index1 = selection.indexes()[0] index2 = self.currentIndex() if index2.row() == index1.row(): index2 = selection.last().indexes()[-1] self.is_reversed = True new_selection.append(QtCore.QItemSelectionRange(index1)) new_selection.append(QtCore.QItemSelectionRange(index2)) selection = new_selection else: for index in selection.indexes(): LOGGER.debug("index = %s", index) QtCore.QItemSelectionModel.select(self, selection, command)
def onOpenMeasurementLog(self, traceCreationList): """Called when traceui emits signal to open the corresponding measurement log entry""" self.show() self.raise_() self.activateWindow() measurementDict = self.measurementModel.container.measurementDict measurements = self.measurementModel.measurements selection = QtCore.QItemSelection() self.measurementTableView.selectionModel().select( selection, QtCore.QItemSelectionModel.Clear) #clear selection leftInd = None for traceCreation in traceCreationList: measurement = measurementDict.get(traceCreation) row = measurements.index( measurement) if measurement in measurements else -1 if row >= 0: leftInd = self.measurementModel.index(row, 0) rightInd = self.measurementModel.index( row, self.measurementModel.columnCount() - 1) selection.select( leftInd, rightInd) #add the specified measurement to the selection self.measurementTableView.selectionModel().select( selection, QtCore.QItemSelectionModel.Select) #select full selection if leftInd: self.measurementTableView.scrollTo( leftInd) #scroll to left column of last measurement in list self.measurementTableView.setFocus(True)
def save_entry(self, apply_capitalization=False): new_row = self.editor.entry() new_id = self.model.create_entry( apply_capitalization=apply_capitalization, **new_row) self.table.update() if DEBUG: sys.stdout.write(("new_id {0}".format(new_id)) + os.linesep) for row in range(self.model.rowCount()): new_index = self.table.model().index(row, 0) if self.model.data(new_index) == new_id: if DEBUG: sys.stdout.write( ("new_index {0}, row {1}".format(new_index, row)) + os.linesep) break else: row = None if DEBUG: sys.stdout.write("row not found" + os.linesep) if row is not None: selection = core.QItemSelection() selection.append( core.QItemSelectionRange( self.table.model().index(new_index.row(), 0), self.table.model().index( new_index.row(), self.table.model().columnCount() - 1))) self.table.selectionModel().select( selection, core.QItemSelectionModel.ClearAndSelect) self.table.scrollTo(new_index) self.editor.update_completer(new_row['activity']) self._db.save_changes() self.update_interface() core.QTimer.singleShot(0, partial(self.clear_entry, False))
def load_checklists(self, checklists: typing.List[models.CheckList]): self.checklists_tv.selectionModel().select( QtCore.QItemSelection(), QtCore.QItemSelectionModel.Clear) self.model.clear() self.model.setHorizontalHeaderLabels([ i.name.replace('_', ' ').capitalize() for i in ChecklistModelColumn ]) for row_index, checklist in enumerate(checklists): checklist: models.CheckList identifier_item = QtGui.QStandardItem(str(checklist.identifier)) identifier_item.setData( checklist, role=CustomDataRoles.CHECKLIST_DOWNLOADER_IDENTIFIER.value) self.model.setItem(row_index, ChecklistModelColumn.IDENTIFIER.value, identifier_item) self.model.setItem(row_index, ChecklistModelColumn.NAME.value, QtGui.QStandardItem(checklist.name)) self.model.setItem( row_index, ChecklistModelColumn.DATASET_TYPE.value, QtGui.QStandardItem(checklist.dataset_type.value)) self.model.setItem( row_index, ChecklistModelColumn.APPLICABLE_TO.value, QtGui.QStandardItem(checklist.validation_artifact_type.value)) # self.checklists_tv.setModel(self.model) self.checklists_tv.setColumnHidden( ChecklistModelColumn.IDENTIFIER.value, True) header = self.checklists_tv.header() header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
def selectImage(self, row): sel_model = self.ui.images_tbl.selectionModel() index1 = self.image_model.index(row, 0) index2 = self.image_model.index(row, ImagesModel.COLUMNS - 1) sel_model.select( QtCore.QItemSelection(index1, index2), QtCore.QItemSelectionModel.ClearAndSelect | QtCore.QItemSelectionModel.Current)
def select_all(self): row_count = self.filter_model.rowCount() column_count = self.filter_model.columnCount() topLeft = self.filter_model.index(0, 0) bottomRight = self.filter_model.index(row_count - 1, column_count - 1) selection = QtCore.QItemSelection(topLeft, bottomRight) self.view.selectionModel().select(selection, QtCore.QItemSelectionModel.Select)
def _handle_select_all_measurements(self): row_count = self._measurement_model.rowCount() column_count = self._measurement_model.columnCount() topLeft = self._measurement_model.index(0, 0) bottomRight = self._measurement_model.index(row_count - 1, column_count - 1) selection = QtCore.QItemSelection(topLeft, bottomRight) self.measurement_view.view.selectionModel().select( selection, QtCore.QItemSelectionModel.Select)
def _apply_selection_to_full_row(self): rows = list() selection = QtCore.QItemSelection() for idx in self.selectedIndexes(): if idx.row() not in rows: rows.append(idx.row()) selection.append(QtWidgets.QItemSelectionRange(idx)) self.selectionModel().select(selection, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.ClearAndSelect)
def __select_row(self, row_idx): left_idx = self.model.index(row_idx, 0, QtCore.QModelIndex()) right_idx = self.model.index(row_idx, self.model.columnCount() - 1) row_selection = QtCore.QItemSelection() row_selection.select(left_idx, right_idx) self.selection_model.setCurrentIndex( left_idx, QtCore.QItemSelectionModel.Rows) self.selection_model.select( row_selection, QtCore.QItemSelectionModel.Select)
def __updateSelectionInView(self, page): """ Makes the current selection in internal widget used to display the data values """ selModel = self._tableView.selectionModel() if selModel is not None: pageSize = self._pagingInfo.pageSize m = self._pageItemModel sel = qtc.QItemSelection() for row in range(page * pageSize, (page + 1) * pageSize): if row in self._selection: sel.append( qtc.QItemSelectionRange( m.index(row % pageSize, 0), m.index(row % pageSize, m.columnCount() - 1))) allSel = qtc.QItemSelection( m.index(0, 0), m.index(pageSize - 1, m.columnCount() - 1)) selModel.select(allSel, qtc.QItemSelectionModel.Deselect) if not sel.isEmpty(): selModel.select(sel, qtc.QItemSelectionModel.Select)
def _move(self, rows: List[int], diff: int) -> None: for row in rows: item = self.to_model.takeItem(row, 0) self.to_model.removeRow(row) self.to_model.insertRow(row + diff, item) selection = C.QItemSelection() for row in rows: index = self.to_model.index(row + diff, 0) selection.select(index, index) self.to_list.selectionModel().select( selection, C.QItemSelectionModel.ClearAndSelect) self.load_pictures_task.run()
def select_by_colnames(self, cnames): new_selection = QtCore.QItemSelection() flags = (QtCore.QItemSelectionModel.Select | QtCore.QItemSelectionModel.Rows) for c in cnames: index = self.model().match(self.model().index(0, 0), TwoLevelTreeModel.SubDataRole, c, 1, QtCore.Qt.MatchRecursive) for ind in index: new_selection.select(ind, ind) self.selectionModel().clearSelection() self.selectionModel().select(new_selection, flags)
def onModelItemsReordered(self): new_selection = QtCore.QItemSelection() new_index = QtCore.QModelIndex() for item in self.model().lastDroppedItems: row = self.model().rowForItem(item) if row is None: continue new_index = self.model().index(row, 0, QtCore.QModelIndex()) new_selection.select(new_index, new_index) self.clearSelection() flags = QtCore.QItemSelectionModel.ClearAndSelect | \ QtCore.QItemSelectionModel.Rows | \ QtCore.QItemSelectionModel.Current self.select(new_selection, flags) self.setCurrentIndex(new_index, flags)
def set_chosen_2nd_slot(self, slot): ''' user has clicked on a secondary slot - we need to switch the appointments over! ''' LOGGER.debug("set_chosen_2nd_slot %s", slot) model = self.appointment_model.selection_model selection = model.selection() selection.swap(0, 1) model.select(selection, model.ClearAndSelect) self.selection_changed( self.appointment_model.selection_model.selection()) self.appointment_model.selection_model.emitSelectionChanged( selection, QtCore.QItemSelection()) slot.is_primary = True self.set_chosen_slot(slot) self.chosen_slot_changed.emit()
def set_selected_appointments(self, selected_apps): ''' programatically make a selection (to sync with other ways of selecting an appointment, eg pt_diary) ''' selection = QtCore.QItemSelection() # for app in sorted(selected_apps, # key=lambda x: x.unscheduled, reverse=True): for app in selected_apps: LOGGER.debug("Need to reselect appointment %s", app) try: row = self.items.index(app) index = self.index(row) selection.append(QtCore.QItemSelectionRange(index)) except ValueError: # app not in list pass self.selection_model.select(selection, QtCore.QItemSelectionModel.Select)
def lines_updated_restore_selection(self): selection_model = self.selectionModel() indexes = [ self.log_model.index_from_revid(revid) for revid in self.lines_updated_selection ] selection_model.clear() if self.lines_updated_selection_current: current_index = self.log_model.index_from_revid( self.lines_updated_selection_current) if current_index: self.setCurrentIndex(current_index) if not len(indexes) == 0 and indexes[0]: if not indexes[1]: indexes[1] = indexes[0] selection = QtCore.QItemSelection(*indexes) selection_model.select(selection, (QtCore.QItemSelectionModel.SelectCurrent | QtCore.QItemSelectionModel.Rows))
def select_tree_item(self, item): selectionModel = self.classTree.selectionModel() flags = QtCore.QItemSelectionModel.Select | QtCore.QItemSelectionModel.Rows selected = QtCore.QItemSelection() if item.parent() is None: index = self.classModel.indexFromItem(item) else: category_item = item.parent() rows = category_item.rowCount() category_index = self.classModel.indexFromItem(category_item) row = 0 for i in range(rows): child = category_item.child(i, 0) if child.data(0) == item.data(0): row = i break index = self.classModel.index(row, 0, category_index) selectionModel.clearSelection() selectionModel.select(index, flags) self.classTree.setCurrentIndex(index)
def _el_group_view_sel_change(self, selected, deselected): if self._selection_disable: return sm = self.el_group_view.view.selectionModel() rows = [r.row() for r in sm.selectedRows()] m_ids = set() for r in rows: m_ids = m_ids.union(set(self._electrode_groups[r].measurement_ids)) sm = self.measurement_view.view.selectionModel() self._selection_disable = True sm.clear() for i in m_ids: column_count = self._measurement_model.columnCount() topLeft = self._measurement_model.index(i, 0) bottomRight = self._measurement_model.index(i, column_count - 1) selection = QtCore.QItemSelection(topLeft, bottomRight) sm.select(selection, QtCore.QItemSelectionModel.Select) self._selection_disable = False
def move_contrib_row_up(self): if (self.contributorModel.rowCount() < 2): TDBUtil.make_msgbox("", "need at least 2 rows to move", QtWidgets.QMessageBox.Information) return sel_idxs = self.tableViewContributor.selectedIndexes() if (len(sel_idxs) > 0): curr_row_model_index = sel_idxs[0] active_row = curr_row_model_index.row() active_col = curr_row_model_index.column() if (active_row == 0): print("Top most row - cannot move further") return curr_item_list = self.contributorModel.takeRow(active_row) self.contributorModel.insertRow(active_row - 1, curr_item_list) #selection code sel_model = self.tableViewContributor.selectionModel() # recompute mi from model print("---------") print("({},{})".format(active_row, active_col)) print("({},{})".format(active_row - 1, active_col)) # active_row = curr_row_model_index.row() # active_col = curr_row_model_index.column() model_index_topLeft = self.contributorModel.index( active_row - 1, active_col, QtCore.QModelIndex()) model_index_topRight = self.contributorModel.index( active_row - 1, active_col, QtCore.QModelIndex()) selection = QtCore.QItemSelection(model_index_topLeft, model_index_topRight) # sel_model.clear() sel_model.select(selection, QtCore.QItemSelectionModel.ClearAndSelect) else: TDBUtil.make_msgbox("", "Please select a publisher to move.", QtWidgets.QMessageBox.Information)
def _handleLink(self, link): """Handle a link in the text.""" action, index = link.split(':', 1) index = int(index) info = self.editor.model().extTagInfos[index] if action == 'add': tagwidgets.AddTagTypeDialog.addTagType(info.tag) elif action == 'delete': levels.editor.changeTags({ el: tags.SingleTagDifference(info.tag, removals=el.tags[info.tag]) for el in info.elements }) elif action == 'select': # Construct a QItemSelection storing the whole selection and add it to the model at once. # Otherwise a selectionChanged signal would be emitted after each selected wrapper. itemSelection = QtCore.QItemSelection() for wrapper in self.editor.model().getAllNodes(): if wrapper.element in info.elements: index = self.editor.model().getIndex(wrapper) itemSelection.select(index, index) self.editor.selectionModel().select( itemSelection, QtCore.QItemSelectionModel.ClearAndSelect)
def _selectDroppedRows(self, parent, start, end): self.selectionModel().select( QtCore.QItemSelection(self.model().index(start, 0, parent), self.model().index(end, 0, parent)), QtCore.QItemSelectionModel.ClearAndSelect) self.setFocus(Qt.MouseFocusReason)