def setEditorData(self, editor: QWidget, index: QModelIndex): #currentDate = datetime.date(index.data(Qt.EditRole)) if (index.data(Qt.EditRole) != None): currentDate = (index.data(Qt.EditRole)).toPython() day = currentDate.day month = currentDate.month year = currentDate.year editor.setDate(QDate(year, month, day))
def onCurrentChanged(self, currentIdx: QtCore.QModelIndex, prevIdx: QtCore.QModelIndex): """connected to selection model - convert model indices to branches, then emit top-level signal""" newBranch = currentIdx.data(treeObjRole) prevBranch = prevIdx.data(treeObjRole) self.currentBranchChanged.emit({ "oldBranch": prevBranch, "newBranch": newBranch })
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex): if index.column() == 3: v = index.data(Qt.CheckStateRole) self.drawCheck(painter, option, option.rect, Qt.Checked if v else Qt.Unchecked) elif index.column() == 2: if self.cond["RESULT_DISPLAY_QUEST"]: super().paint(painter, option, index) else: v = index.data(Qt.CheckStateRole) self.drawCheck(painter, option, option.rect, Qt.Checked if v else Qt.Unchecked) else: super().paint(painter, option, index)
def setEditorData(self, editor: '_IntervalWidget', index: QModelIndex) -> None: bins: List[pd.Timestamp] obj = index.data(Qt.EditRole) if obj: bins, byDate, byTime = index.data(Qt.EditRole) if bins: dataBins: List[QDateTime] = list(map(toQtDateTime, bins)) editor.setOptions(dataBins, byDate, byTime) return # Make two row by default (minimum required to define a range) editor.addRow() editor.addRow()
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex): """Paint a cell according index and option Args: painter (QPainter) option (QStyleOptionViewItem) index (QModelIndex) """ # Draw background selections if option.state & QStyle.State_Selected: select_color = option.palette.color(QPalette.Normal, QPalette.Highlight) text_color = option.palette.color(QPalette.Normal, QPalette.BrightText) painter.fillRect(option.rect, select_color) else: text_color = option.palette.color(QPalette.Normal, QPalette.Text) # get icon and color background icon = index.data(Qt.DecorationRole) icon_color = index.data(Qt.BackgroundColorRole) # draw icon background area = QRect(option.rect.x(), option.rect.y(), option.rect.height(), option.rect.height()) painter.setPen(Qt.NoPen) painter.setBrush(QColor(icon_color)) painter.drawRect(area) # Draw icon if icon: icon_area = area.adjusted(3, 3, -3, -3) painter.drawPixmap(icon_area, icon.pixmap(icon_area.size())) # Draw text text_rect = option.rect text_rect.setLeft(option.rect.height() + 3) light_font = QFont() dark_font = QFont() word = index.data(Qt.DisplayRole) font = QFont("monospace") painter.setFont(font) painter.setPen(QPen(text_color)) painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, word)
def paint( self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex ) -> None: # Draw the list item with all the default selection styling, but with an # invalid index so text formatting is left to us. super().paint(painter, option, QModelIndex()) rect = option.rect.adjusted( self.HMARGIN, self.VMARGIN, -self.HMARGIN, -self.VMARGIN ) with painter_context(painter): painter.setFont(self.get_font(option)) icon: Optional[QIcon] = index.data(Qt.DecorationRole) if icon is not None: icon.paint( painter, rect, Qt.AlignLeft | Qt.AlignVCenter, self.icon_mode(option), self.icon_state(option), ) rect = rect.adjusted(self.icon_size(option).width() + self.HMARGIN, 0, 0, 0) painter.drawText(rect, Qt.AlignLeft, self.first_row_text(index)) line2 = rect.adjusted(0, rect.height() / 2, 0, rect.height() / 2) painter.drawText(line2, Qt.AlignLeft, self.second_row_text(index)) clients = self.num_clients(index) if clients: painter.drawText(rect, Qt.AlignRight, f"Player Slots: {clients}")
def paint( self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex ) -> None: # Draw the list item with all the default selection styling, but with an # invalid index so text formatting is left to us. super().paint(painter, option, QModelIndex()) rect = option.rect.adjusted( self.HMARGIN, self.VMARGIN, -self.HMARGIN, -self.VMARGIN ) with painter_context(painter): painter.setFont(self.get_font(option)) icon: Optional[QIcon] = index.data(Qt.DecorationRole) if icon is not None: icon.paint( painter, rect, Qt.AlignLeft | Qt.AlignVCenter, self.icon_mode(option), self.icon_state(option), ) rect = rect.adjusted(self.icon_size(option).width() + self.HMARGIN, 0, 0, 0) row_height = rect.height() / self.rows for row in range(self.rows): y = row_height * row location = rect.adjusted(0, y, 0, y) painter.drawText(location, Qt.AlignLeft, self.text_for(index, row, 0)) if self.columns == 2: painter.drawText( location, Qt.AlignRight, self.text_for(index, row, 1) )
def replace_command(self, index: QModelIndex, undo_parent: QUndoCommand = None): search_txt = self.edit_search.text() replace_txt = self.edit_replace.text() item_text = index.data(role=Qt.DisplayRole) if self.check_case.isChecked(): flags = 0 else: flags = re.IGNORECASE try: new_text = re.sub(QRegularExpression.escape(search_txt), replace_txt, item_text, flags=flags) except Exception as e: LOGGER.error(e) return if new_text == item_text: return return ItemEditUndoCommand(item_text, new_text, index, undo_parent, editing_done=False)
def setEditorData(self, editor: QtWidgets.QLineEdit, index: QtCore.QModelIndex): """ Populate the editor with data if editing an existing field. """ data = index.data(QtCore.Qt.DisplayRole) value = float(data) if data and not math.isnan(data) else 0 editor.setText(str(value))
def setData(self, index: QModelIndex, value: Any, role: int = ...) -> bool: # NOTE: does not support changing type for now (only name) if not index.isValid(): return False if role == Qt.EditRole: # Change attribute name if index.column() == self.nameColumn: value: str = value.strip() if not value or value == index.data(Qt.DisplayRole): return False if value in self._frameModel.frame.colnames: gui.notifier.addMessage( 'Rename error', 'New name "{}" is duplicate'.format(value), QMessageBox.Critical) return False return self._frameModel.setHeaderData(index.row(), Qt.Horizontal, value, Qt.EditRole) # Toggle checkbox state elif index.column() == self.checkboxColumn: i: int = index.row() self._checked[i] = value self.dataChanged.emit(index, index) self.headerDataChanged.emit(Qt.Horizontal, index.column(), index.column()) return True return False
def __pressed(self, data: QModelIndex) -> None: node: NavModel.TreeNode = data.data(Qt.UserRole) text: AnyStr = node.text parentText: AnyStr = node.parentText parentIndex: int = self.parentItem.index(parentText) # 默认没有子节点则父节点为子节点 index: int = self.__childItem[parentIndex].index( text) if parentIndex >= 0 else self.parentItem.index(text) # 找出子节点在子节点队列中的索引 childIndex: int = -1 for i in range(self.__childItem.__len__()): item: List[AnyStr] = self.__childItem[i] ok: bool = False for subItem in item: childIndex += 1 # 找到了对应子节点 if subItem == text: ok = True break if ok: break # 如果当前节点是父节点则将子节点索引置为-1 if parentIndex == -1: childIndex = -1 self.pressed_curName.emit(text, parentText) # 当前节点名称+父节点名称 self.pressed_curIndex.emit(index, parentIndex) # 当前节点索引+父节点索引 self.pressed_allIndex.emit(childIndex) # 整个子节点中对应的索引
def setEditorData(self, editor: QtWidgets.QLineEdit, index: QtCore.QModelIndex): """ Populate the editor with data if editing an existing field. """ value = index.data(QtCore.Qt.DisplayRole) # Avoid setting 'None' type value as a string value = str(value) if value else "" editor.setText(value)
def _view_item_pressed(self, index: QModelIndex): if not self.last_view: return LOGGER.debug(index.data(Qt.DisplayRole)) src_index = self.search_view.model().mapToSource(index) proxy_index = self.last_view.model().mapFromSource(src_index) self.last_view.scrollTo(proxy_index, QAbstractItemView.PositionAtCenter)
def deckListClicked(self, index: QtCore.QModelIndex): #TODO: Attribute Error if I start and press Select Deck without moving selection print(self.deckListIndex, index.row()) self.ui.lineEdit_searchQuery.clear() if index.row() == self.deckListIndex: print("Nothing to do") else: self.ui.checkBox_starredOnly.setChecked(False) self.deckListIndex = index.row() self.nameOfCurrentDeck = index.data() self.loadWordTable() self.ui.label_selectedDeck.setText(index.data()) self.ui.tableView.setColumnWidth(2, 30) self.ui.tableView.setColumnWidth(3, 200) self.ui.tableView.setColumnWidth(4, 200) self.ui.tableView.setColumnWidth(5, 200) self.ui.buttonBox_wordList.setDisabled(True) self.ui.tableView.setSortingEnabled(True)
def paint(self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> None: """set the current branch from index more complex painting for deltas, references etc is handled by view as a post process, was just easier that way """ self.branch = index.data(treeObjRole) super(TreeNameDelegate, self).paint(painter, option, index)
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget: color = index.data(Qt.DecorationRole) if not color or isinstance(color, QColor): editor = ColorEditWidget(parent) editor.color_picked.connect(self.color_picked) return editor else: logger.warning("ColorDelegate invoked on non-color") return super().createEditor(parent, option, index)
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: node: NavModel.TreeNode = index.data( Qt.UserRole ) # NavModel::TreeNode *node = (NavModel::TreeNode *)index.data(Qt::UserRole).toULongLong(); # 设置最小的宽高 parent: bool = node.level == 1 size: QSize = QSize( 50, self.__nav.parentHeight if parent else self.__nav.childHeight) return size
def _on_row_changed(self, current: QModelIndex, previous: QModelIndex): """Slot received when user select a new item in the list. This is used to update the panel Args: current (QModelIndex): the selection index previous (QModelIndex): UNUSED """ description = current.data(Qt.ToolTipRole) self.panel.setText(description)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex): # Change table item foreground (pen color) to red color if it's highlighted highlighted_palette = False if option.state & QStyle.State_Selected: if option.state & QStyle.State_Active: painter.fillRect(option.rect, option.palette.highlight()) highlighted_palette = True elif not (option.state & QStyle.State_HasFocus): painter.fillRect(option.rect, option.palette.background()) if index.data(TableItemDataRole.HIGHLIGHT): painter.setPen( QColor(255, 128, 128) if highlighted_palette else Qt.red) else: painter.setPen(Qt.black) painter.drawText(option.rect, Qt.AlignCenter, index.data())
def _on_tree_selection_changed(self, index: QModelIndex, _previous): data = index.data(QtCore.Qt.UserRole) if self.terrain_mode: self.grid.selected_tile = data self.tile_form.update_target(data) else: if type(data) == PropertyContainer: self.grid.select_spawn(data) self.selected_faction = None else: self.selected_faction = data
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex): if True: if index.column() == 3: self.parent().openPersistentEditor(index) elif index.column() == 2: v = index.data(Qt.CheckStateRole) self.drawCheck(painter, option, option.rect, Qt.Checked if v else Qt.Unchecked) else: super().paint(painter, option, index) else: super().paint(painter, option, index)
def setEditorData(self, editor: QtWidgets.QWidget, index: QtCore.QModelIndex): """ Populate the editor with data if editing an existing field. """ dialog = editor.findChild(OrderedListInputDialog) value = index.data(QtCore.Qt.DisplayRole) values = [] if not value else [i.lstrip() for i in value.split(",")] parent = self.parent() if getattr(parent, "table_name") == "activity_parameter": groups = parent.get_activity_groups(index, values) unchecked = dialog.add_items_value(groups) checked = dialog.add_items_value(values, True) dialog.set_items(checked + unchecked)
def setData(self, index: QModelIndex, value: str, role: int = ...) -> bool: if not index.isValid(): return False value = value.strip() if role == Qt.EditRole and value and index.column() == self.nameColumn and \ value != index.data(Qt.EditRole): # TODO: add regex validator self._edits[index.row()] = value else: return False self.dataChanged.emit(index, index) return True
class ViewItemEditUndo(QObject): """ Undo command for view item edits """ def __init__(self, view): super(ViewItemEditUndo, self).__init__(parent=view) self.view = view self.undo_stack = view.undo_stack self.previous_data = '' self.edit_index = QModelIndex() self.reference_index_ls = list() self.org_view_edit = self.view.edit self.view.edit = self._item_edit_wrapper self.org_data_commit = self.view.commitData self.view.commitData = self._data_commit_wrapper @Slot(QModelIndex, object, QEvent) def _item_edit_wrapper(self, index, trigger, event): """ Fetch the start of an edit """ self.org_view_edit(index, trigger, event) if trigger & self.view.editTriggers(): self.view.clear_filter(collapse=False) # Save data previous to editing self.previous_data = index.data() # Save currently edited index self.edit_index = index # Do not fetch the Qt item edit method, continue return False def _data_commit_wrapper(self, editor): """ Fetch user edit data commits to the model """ self.org_data_commit(editor) current_data = self.edit_index.data() if self.previous_data == current_data or current_data is None: # No change detected return # Editor undo cmd undo_cmd = ItemEditUndoCommand(self.previous_data, current_data, self.edit_index) self.undo_stack.push(undo_cmd) self.undo_stack.setActive(True)
def setData(self, index: qc.QModelIndex, value: t.Any, role: int = qq.CheckStateRole) -> bool: if not (index.isValid() or role == qq.CheckStateRole): return False item = index.data(Roles.SourceDataRole) if value == qq.Checked: self._checked.append(item) else: self._checked.remove(item) return True
def setEditorData(self, editor: QtWidgets.QComboBox, index: QtCore.QModelIndex): """Lookup the description text set in the model using the reverse dictionary for the uncertainty choices. Note that the model presents the integer value as a string (the description of the uncertainty distribution), so we cannot simply take the value and set the index in that way. """ value = index.data(QtCore.Qt.DisplayRole) try: value = int(value) if value is not None else 0 except ValueError as e: print("{}, using 0 instead".format(str(e))) value = 0 editor.setCurrentIndex(uc.choices.index(uc[value]))
def textColour( self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex) -> typing.Union[QtGui.QColor, None]: """return a Qt.Color or None in the base, check first for an explicit colour in data, then in palette passing None to QColor gives black, I didn't know that """ # check for colour set as data dataCol = index.data(QtCore.Qt.TextColorRole) # fall back to palette coour paletteCol: QtGui.QColor = option.palette.text().color() #print("base textColour", dataCol, paletteCol) textCol = dataCol or paletteCol return textCol
def createWorkbenchPopupMenu(self, index: QModelIndex) -> None: # Create a popup menu when workbench is right-clicked over a valid frame name # Menu display delete and remove options frameName: str = index.data(Qt.DisplayRole) pMenu = QMenu(self) # Reuse MainWindow actions csvAction = self.parentWidget().aWriteCsv pickleAction = self.parentWidget().aWritePickle # Set correct args for the clicked row csvAction.setOperationArgs(w=self.workbenchModel, frameName=frameName) pickleAction.setOperationArgs(w=self.workbenchModel, frameName=frameName) deleteAction = QAction('Remove', pMenu) deleteAction.triggered.connect( lambda: self.workbenchModel.removeRow(index.row())) pMenu.addActions([csvAction, pickleAction, deleteAction]) pMenu.popup(QtGui.QCursor.pos())
def paint(self, painter: QtGui.QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None: checked: bool = index.data(Qt.DisplayRole) options = QStyleOptionButton() if (index.flags() & Qt.ItemIsEditable) > 0: options.state |= QStyle.State_Enabled else: options.state |= QStyle.State_ReadOnly if checked: options.state |= QStyle.State_On else: options.state |= QStyle.State_Off options.rect = self.__getCheckboxRect(option) if not (index.flags() & Qt.ItemIsEditable): options.state |= QStyle.State_ReadOnly QApplication.style().drawControl(QStyle.CE_CheckBox, options, painter)
def setEditorData(self, editor: QtWidgets.QWidget, index: QtCore.QModelIndex): """ Populate the editor with data if editing an existing field. """ dialog = editor.findChild(FormulaDialog) data = index.data(QtCore.Qt.DisplayRole) parent = self.parent() # Check which table is asking for a list if getattr(parent, "table_name", "") in self.ACCEPTED_TABLES: items = parent.get_usable_parameters() dialog.insert_parameters(items) dialog.formula = data interpreter = parent.get_interpreter() dialog.insert_interpreter(interpreter) # Now see if we can construct a (partial) key if hasattr(parent, "key"): # This works for exchange tables. dialog.insert_key(parent.key) elif hasattr(parent, "get_key"): dialog.insert_key(parent.get_key())