def data(self, index, role=Qt.DisplayRole, field=''): row = index.row() if not index.isValid(): return None operation = LedgerTransaction().get_operation( self._data[index.row()]['op_type'], self._data[index.row()]['id'], self._data[index.row()]['subtype']) if role == Qt.DisplayRole: return self.data_text(operation, index.column()) if role == Qt.FontRole and index.column() == 0: # below line isn't related with font, it is put here to be called for each row minimal times (ideally 1) self._view.setRowHeight( row, self._view.verticalHeader().defaultSectionSize() * operation.view_rows()) font = QFont() font.setBold(True) return font if role == Qt.ForegroundRole and self._view.isEnabled(): if index.column() == 0: return QBrush(operation.label_color()) elif index.column() == 5: if operation.reconciled(): return QBrush(CustomColor.Blue) if role == Qt.TextAlignmentRole: if index.column() == 0: return int(Qt.AlignCenter | Qt.AlignVCenter) if index.column() == 4 or index.column() == 5: return int(Qt.AlignRight) return int(Qt.AlignLeft) if role == Qt.UserRole: # return underlying data for given field extra parameter return self._data[index.row()][field]
def __update_file_status(self, item: EssStandardItem): stat = get_from_essharp(item.accessibleText(), "s") if not len(stat): logging.error("get_from_essharp fail: " + item.accessibleText()) return parent = item.parent() if parent is None: name_col = self.__ess_file_model.item( item.row(), ITEM_PROPERTIES.index("user")) date_col = self.__ess_file_model.item( item.row(), ITEM_PROPERTIES.index("date")) else: name_col = parent.child(item.row(), ITEM_PROPERTIES.index("user")) date_col = parent.child(item.row(), ITEM_PROPERTIES.index("date")) if stat["ischeckout"]: name_col.setText(stat["checkout_info"]["user_name"]) date_col.setText(stat["checkout_info"]["date"]) item.setForeground(QBrush(QColor("red"))) set_icon(item, u":/checkout/checkoutline02.svg") else: name_col.setText(stat["version_info"]["user_name"]) date_col.setText(stat["version_info"]["date"]) item.setForeground(QBrush(QColor("black"))) set_icon(item, u":/file/file.svg")
def brushChanged(self): style = Qt.BrushStyle( self.brushStyleComboBox.itemData( self.brushStyleComboBox.currentIndex(), IdRole)) if style == Qt.LinearGradientPattern: linearGradient = QLinearGradient(0, 0, 100, 100) linearGradient.setColorAt(0.0, Qt.white) linearGradient.setColorAt(0.2, Qt.green) linearGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(linearGradient)) elif style == Qt.RadialGradientPattern: radialGradient = QRadialGradient(50, 50, 50, 70, 70) radialGradient.setColorAt(0.0, Qt.white) radialGradient.setColorAt(0.2, Qt.green) radialGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(radialGradient)) elif style == Qt.ConicalGradientPattern: conicalGradient = QConicalGradient(50, 50, 150) conicalGradient.setColorAt(0.0, Qt.white) conicalGradient.setColorAt(0.2, Qt.green) conicalGradient.setColorAt(1.0, Qt.black) self.renderArea.setBrush(QBrush(conicalGradient)) elif style == Qt.TexturePattern: self.renderArea.setBrush(QBrush(QPixmap(':/images/brick.png'))) else: self.renderArea.setBrush(QBrush(Qt.green, style))
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) center = QPointF(self.width() / 2, self.height() / 2) radius = self.radius() ellipse_line_width = self.radius() * 60 / 512 # big ellipse pen = QPen() pen.setWidth(ellipse_line_width) pen.setColor(self.color) painter.setPen(pen) painter.drawEllipse(center, radius - pen.width() / 2, radius - pen.width() / 2) # dots pen = QPen() pen.setColor(QColor(0, 0, 0, 0)) painter.setPen(pen) brush = QBrush() brush.setStyle(Qt.SolidPattern) dot_size = radius * 200 / 1024 color = copy.copy(self.color) self._change_color(painter, brush, color, 0) painter.drawEllipse( QPointF((self.width() - radius - ellipse_line_width / 2) / 2, self.height() / 2), dot_size, dot_size) self._change_color(painter, brush, color, 15) painter.drawEllipse(center, dot_size, dot_size) self._change_color(painter, brush, color, 30) painter.drawEllipse( QPointF((self.width() + radius + ellipse_line_width / 2) / 2, self.height() / 2), dot_size, dot_size)
def data_background(self, row, column, enabled=True): factor = 100 if enabled else 125 if column == 3: if self._data[row]['unreconciled'] > 15: return QBrush(CustomColor.LightRed.lighter(factor)) if self._data[row]['unreconciled'] > 7: return QBrush(CustomColor.LightYellow.lighter(factor))
def data_foreground(self, row, column): if column == 0: try: return QBrush( self.OperationSign[self._data[row]['type'], self._data[row]['subtype']][1]) except KeyError: return QBrush(CustomColor.LightRed) if column == 5: if self._data[row]['reconciled'] == 1: return QBrush(CustomColor.Blue)
def __init__(self, name="?", r=10): super().__init__() self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemIsFocusable) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges) self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.setAcceptHoverEvents(True) # define circle shape: w = 2 * r + 2 self.el = QGraphicsEllipseItem(0, 0, w, w) self.el.setBrush(QBrush(QColor("white"))) shadow = QGraphicsDropShadowEffect() shadow.setOffset(4) self.el.setGraphicsEffect(shadow) self.el.setParentItem(self) # define node label shape: self.label = QGraphicsTextItem(name) self.label.setDefaultTextColor(QColor("blue")) self.label.setFlag(QGraphicsItem.ItemIsSelectable) self.label.setParentItem(self) self.el.setZValue(1.0) self.label.setZValue(2.0) center = self.center() - self.label.boundingRect().center() self.label.setPos(self.mapFromScene(center)) self.setZValue(1.0) self.cx = []
def __init__(self, block): super().__init__() self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemIsFocusable) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges) self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.setAcceptHoverEvents(True) # define code text shape: self.code = QGraphicsTextItem() self.code.setHtml(block) f = QFont("Monospace") f.setPointSize(8) self.code.setFont(f) self.code.setParentItem(self) # define circle shape: self.codebox = QGraphicsRectItem(self.code.boundingRect().adjusted( -2, -2, 2, 2)) self.codebox.setBrush(QBrush(QColor("#fdf6e3"))) shadow = QGraphicsDropShadowEffect() shadow.setOffset(4) self.codebox.setGraphicsEffect(shadow) self.codebox.setParentItem(self) self.codebox.setZValue(1.0) self.code.setZValue(2.0) center = (self.codebox.boundingRect().center() - self.code.boundingRect().center()) self.code.setPos(center) self.setZValue(1.0) self.cx = []
def drawBackground(self, painter: QPainter, rect: QRectF): currentColor = self.backgroundBrush().color() if currentColor != self.backgroundColor: self.setBackgroundBrush(QBrush(self.backgroundColor)) super().drawBackground(painter, rect) if self._zoom <= self.gridZoomThreshold or not self.showGrid: return painter.setPen(QPen(self.gridColor, self.gridThickness)) lines = [] if self.gridSpacing.width() > 0: xStart = rect.left() - rect.left() % self.gridSpacing.width() while xStart <= rect.right(): line = QLineF(xStart, rect.bottom(), xStart, rect.top()) lines.append(line) xStart = xStart + self.gridSpacing.width() if self.gridSpacing.height() > 0: yStart = rect.top() - rect.top() % self.gridSpacing.height() while yStart <= rect.bottom(): line = QLineF(rect.left(), yStart, rect.right(), yStart) lines.append(line) yStart = yStart + self.gridSpacing.height() painter.drawLines(lines)
def initUI(self): self.setWindowTitle("QTableWidget 例子") self.resize(600, 800); conLayout = QHBoxLayout() tableWidget = QTableWidget() tableWidget.setRowCount(30) tableWidget.setColumnCount(4) conLayout.addWidget(tableWidget) for i in range(30): for j in range(4): itemContent = '(%d,%d)' % (i, j) tableWidget.setItem(i, j, QTableWidgetItem(itemContent)) self.setLayout(conLayout) # 遍历表查找对应的item text = "(10,1)" items = tableWidget.findItems(text, QtCore.Qt.MatchExactly) item = items[0] # 选中单元格 # item.setSelected( True) # 设置单元格的背景颜色为红色 item.setForeground(QBrush(QColor(255, 0, 0))) row = item.row() # 滚轮定位过去,快速定位到第17行 tableWidget.verticalScrollBar().setSliderPosition(row)
def paint(self, painter: QPainter): brush = QBrush(QColor("#007430")) painter.setBrush(brush) painter.setPen(Qt.NoPen) painter.setRenderHint(QPainter.Antialiasing) itemSize = self.size() painter.drawRoundedRect(0, 0, itemSize.width(), itemSize.height() - 10, 10, 10) if self.rightAligned: points = [ QPointF(itemSize.width() - 10.0, itemSize.height() - 10.0), QPointF(itemSize.width() - 20.0, itemSize.height()), QPointF(itemSize.width() - 30.0, itemSize.height() - 10.0), ] else: points = [ QPointF(10.0, itemSize.height() - 10.0), QPointF(20.0, itemSize.height()), QPointF(30.0, itemSize.height() - 10.0), ] painter.drawConvexPolygon(points)
def __init__(self, parent=None): super().__init__(parent) self.focus_policy = Qt.StrongFocus self.view_label = QLabel() self.view_label.style_sheet = 'QLabel { background-color : #313D4A; padding : 10px 10px 10px 10px; }' # 354A64 self.view_label.alignment = Qt.AlignCenter self.red_color = QColor(205, 65, 65) self.green_color = QColor(65, 205, 82) transf_widget_size = QSize(28, 12) self.translated_widget = ColoredWidget() self.rotated_widget = ColoredWidget() self.scaled_widget = ColoredWidget() self.translated_widget.set_fixed_size(transf_widget_size) self.rotated_widget.set_fixed_size(transf_widget_size) self.scaled_widget.set_fixed_size(transf_widget_size) self.translated_widget.tool_tip = 'translation was applied' self.rotated_widget.tool_tip = 'rotation was applied' self.scaled_widget.tool_tip = 'scaling was applied' self.translated_widget.brush = QBrush(self.green_color) self.rotated_widget.brush = QBrush(self.red_color) self.scaled_widget.brush = QBrush(self.green_color) transformation_layout = QHBoxLayout() transformation_layout.add_stretch() transformation_layout.add_widget(self.translated_widget) transformation_layout.add_widget(self.rotated_widget) transformation_layout.add_widget(self.scaled_widget) transformation_layout.add_stretch() self.info = QPlainTextEdit() font = self.info.font font.set_family('Courier New') # monospace self.info.font = font self.info.read_only = True self.info.line_wrap_mode = QPlainTextEdit.NoWrap layout = QVBoxLayout(self) layout.add_widget(QLabel('Image information')) layout.add_widget(self.view_label) layout.add_layout(transformation_layout) layout.add_widget(self.info) layout.contents_margins = QtCore.QMargins(0, 0, 0, 0)
def __init__(self, scene, central_widget, gim): super(CustomQGraphicsView, self).__init__(scene, central_widget) # Ustawienia na potrzeby poprawnego rysowania: self.actual_selection: Enum = self.Selection.SELECT self.drawing: bool = False self.preparing: bool = False self.prepare_points: list[QPointF] = [] self.previous_point: QPoint = QPoint(0, 0) # Obiekty na potrzeby sposobu rysowania self.actual_pen: QPen = QPen(QBrush( Qt.black), 1) # QPen: kolor i szerokosc linii + dodatki self.actual_brush: QBrush = QBrush(Qt.darkGreen) # kolor wypełnienia # Model dla itemów sceny self.gim: GraphicItemModel = gim
def paint(self, painter, option, widget=None): qgp = self.getqgp() pen = QPen() pen.setWidth(2) qgp.setPen(pen) qgp.setBrush(QBrush(Qt.NoBrush)) painter.setClipRect(option.exposedRect) qgp.paint(painter, option, widget) lastp = self.points[-1] angle = radians(qgp.path().angleAtPercent(1.0)) angle = angle + pi p = lastp + QPointF( cos(angle - pi / 6.0) * 10, -sin(angle - pi / 6.0) * 10) q = lastp + QPointF( cos(angle + pi / 6.0) * 10, -sin(angle + pi / 6.0) * 10) painter.setBrush(QBrush(QColor("black"))) self.head = QPolygonF([lastp, p, q]) painter.drawPolygon(self.head)
def programListUpdated(self, programs, current_program): print(programs) print(current_program) self.closeWaitDialog() self.programsListModel.clear() for p in programs: item = QStandardItem(p) if p == current_program: item.setForeground(QBrush(QColor(0, 0, 255, 127))) self.programsListModel.appendRow(item)
def refreshInputBgcolor(self): for i in range(self.list_input_files.count()): item = self.list_input_files.item(i) if self._shared_states.hovered is not None and \ item.text() in self._network.predecessors(self._shared_states.hovered): item.setBackground(PRED_COLOR) elif len(list(self._network.successors(item.text()))): item.setBackground(USED_COLOR) else: item.setBackground(QBrush())
def drawGameBox(self, painter): """ Draw game box for the widget """ brush = QBrush(Qt.SolidPattern) brush.setColor(QColor(255, 0, 0)) painter.setBrush(brush) rect = self.contentsRect() painter.drawLine(0, 0, rect.width() - 1, 0) painter.drawLine(rect.width() - 1, 0, rect.width() - 1, rect.height() - 1) painter.drawLine(rect.width() - 1, rect.height() - 1, 0, rect.height()) painter.drawLine(0, rect.height() - 1, 0, 0)
def input_to_shape_item(self, input_stream: QDataStream, item: QAbstractGraphicsShapeItem): self.input_to_graphics_item(input_stream, item) # Type pen = QPen() brush = QBrush() # Read input_stream >> pen input_stream >> brush # Set item.setPen(pen) item.setBrush(brush)
def particle_brush(self, index: int): brush = QBrush() brush.setStyle(Qt.SolidPattern) colors = self.settings.list_value(default_settings.particle_color) colors = [QColor(c) for c in colors] brush.setColor(colors[index % len(colors)]) return brush
def __init__(self, parent): super().__init__(parent) keywordFormat = QTextCharFormat() commentFormat = QTextCharFormat() stringFormat = QTextCharFormat() singleQuotedStringFormat = QTextCharFormat() self.highlightingRules = [] # keyword brush = QBrush(Qt.blue, Qt.SolidPattern) keywordFormat.setForeground(brush) keywordFormat.setFontWeight(QFont.Bold) keywords = keyword.kwlist for word in keywords: pattern = QRegularExpression("\\b" + word + "\\b") rule = HighlightingRule(pattern, keywordFormat) self.highlightingRules.append(rule) # comment brush = QBrush(Qt.green, Qt.SolidPattern) pattern = QRegularExpression("#[^\n]*") commentFormat.setForeground(brush) rule = HighlightingRule(pattern, commentFormat) self.highlightingRules.append(rule) # string brush = QBrush(Qt.red, Qt.SolidPattern) pattern = QRegularExpression("\".*\"") stringFormat.setForeground(brush) rule = HighlightingRule(pattern, stringFormat) self.highlightingRules.append(rule) # singleQuotedString pattern = QRegularExpression("\'.*\'") singleQuotedStringFormat.setForeground(brush) rule = HighlightingRule(pattern, singleQuotedStringFormat) self.highlightingRules.append(rule)
def paint(self, painter, option, index): str_to_symbol = { 'error': pkg_data.ERROR_SYMBOL, 'sleeping': pkg_data.SLEEPING_SYMBOL, 'searching': pkg_data.SEARCH_QUAD_SYMBOL, 'stopped': pkg_data.STOPPED_SYMBOL, 'stopping': pkg_data.WAIT_SYMBOL, } if int(option.state) & QStyle.State_Enabled and int( option.state) & QStyle.State_Selected: brush = QBrush(option.palette.color(option.palette.Highlight)) else: # int(option.state) == QStyle.State_Enabled brush = QBrush(option.palette.color(option.palette.Base)) painter.fillRect(option.rect, brush) size = min(option.rect.width(), option.rect.height()) * 0.85 left = (option.rect.width() - size) / 2 top = option.rect.getCoords()[1] + (option.rect.height() - size) / 2 pixmap = QIcon(str(str_to_symbol[index.data(Qt.DisplayRole)])).pixmap( QSize(size, size)) painter.drawPixmap(QRect(left, top, size, size), pixmap)
def __init__(self, scene: QGraphicsScene, parent: QMainWindow): QGraphicsView.__init__(self, scene, parent) self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0)) self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect)) self.setParent(parent) self.app = self.parent() self.crop_btn = self.parent().crop_button self.mouse_down = False self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern)) self.mouse_pos = QPoint(0, 0) self.adjustment = '' self.annotation = False
def __init__(self, parent=None): super(RenderArea, self).__init__(parent) self.pen = QPen() self.brush = QBrush() self.pixmap = QPixmap() self.shape = RenderArea.Polygon self.antialiased = False self.transformed = False self.pixmap.load(':/images/qt-logo.png') self.setBackgroundRole(QPalette.Base) self.setAutoFillBackground(True)
def mousePressEvent(self, event: QMouseEvent): # pylint: disable=invalid-name """Mouse event handler; begins a crop action""" self.mouse_down = True self.mouse_pos = self.mapToScene(event.pos()).toPoint() if self.crop_btn.isChecked() or self.annotation: self.crop_rect.setTopLeft(self.mapToScene(event.pos()).toPoint()) self.scene().addItem(self.g_rect) if self.annotation: self.g_rect.setPen(QPen(Qt.magenta, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.magenta, Qt.Dense4Pattern)) elif self.hasMouseTracking() and self.g_rect.isUnderMouse: self.adjustment = self.edge(event.pos)[1] else: QGraphicsView.mousePressEvent(self, event)
def reset(self): self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0)) self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect)) self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern)) self.setMouseTracking(False) self.unsetCursor() self.mouse_pos = QPoint(0, 0) self.adjustment = '' self.mouse_down = False if self.crop_btn.isChecked(): self.app.reload() self.setCursor(Qt.CrossCursor) if self.annotation: self.setCursor(Qt.CrossCursor)
def toggle_attached(self): legend = self.chart.legend() if legend.isAttachedToChart(): legend.detachFromChart() legend.setBackgroundVisible(True) legend.setBrush(QBrush(QColor(128, 128, 128, 128))) legend.setPen(QPen(QColor(192, 192, 192, 192))) self.show_legend_spinbox() self.update_legend_layout() else: legend.attachToChart() legend.setBackgroundVisible(False) self.hideLegendSpinbox() self.update()
def initUI(self): self.setWindowTitle("QTableWidget 例子") self.resize(430, 230); conLayout = QHBoxLayout() tableWidget = QTableWidget() tableWidget.setRowCount(4) tableWidget.setColumnCount(3) conLayout.addWidget(tableWidget) tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '体重(kg)']) newItem = QTableWidgetItem("张三") newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 0, newItem) newItem = QTableWidgetItem("男") newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 1, newItem) newItem = QTableWidgetItem("160") newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 2, newItem) self.setLayout(conLayout)
def _initialise(self): """ Draws the login page. """ self.setGeometry(self.left, self.top, self.width, self.height) layout = QGridLayout() # Set background image image = QImage(IMAGES_FILE_PATH + "login.jpg") image_scaled = image.scaled(QSize( self.width, self.height)) # resize Image to widgets size palette = QPalette() palette.setBrush(QPalette.Window, QBrush(image_scaled)) self.setPalette(palette) # Set username label label_name = QLabel('<font size="3"> Käyttäjätunnus </font>') self.lineEdit_username = QLineEdit() self.lineEdit_username.setPlaceholderText('Anna käyttäjätunnus') layout.addWidget(label_name, 0, 0) layout.addWidget(self.lineEdit_username, 0, 1) # Set password label label_password = QLabel('<font size="3"> Salasana </font>') self.lineEdit_password = QLineEdit() self.lineEdit_password.setPlaceholderText('Anna salasana') layout.addWidget(label_password, 1, 0) layout.addWidget(self.lineEdit_password, 1, 1) button_login = QPushButton('Kirjaudu') button_login.clicked.connect(self._check_password) layout.addWidget(button_login, 2, 0, 1, 2) layout.setRowMinimumHeight(2, 10) button_create = QPushButton('Luo uusi käyttäjä') button_create.clicked.connect(self._handle_show_create_user_view) layout.addWidget(button_create, 3, 0, 1, 2) layout.setRowMinimumHeight(2, 10) # Draw close button button_close = QPushButton('Lopeta') button_close.clicked.connect(self._handle_end) layout.addWidget(button_close, 4, 0, 1, 2) layout.setRowMinimumHeight(1, 10) layout.setContentsMargins(600, 400, 600, 400) self.setLayout(layout)
def mark_brush(self, index: int): if self.settings.boolean_value( default_settings.same_mark_color_with_particle): return self.particle_brush(index) else: brush = QBrush() colors = self.settings.list_value(default_settings.mark_color) colors = [QColor(c) for c in colors] brush.setStyle(Qt.SolidPattern) brush.setColor(colors[index % len(colors)]) return brush
def paint(self, painter, option, widget=None): """ Paint the node in the graphic view. """ painter.setPen(QPen(QColor(128, 128, 128), 1.0, Qt.SolidLine)) for cell_rect in self.cell_rects(): painter.drawRect(cell_rect) if self.isSelected(): painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QBrush(QColor(255, 255, 255, 255))) painter.setPen( QPen(QColor(0, 0, 0, 255), 1.0, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) ) for handle, rect in self.handles.items(): if self.selected_handle is None or handle == self.selected_handle: painter.drawEllipse(rect)