def paintEvent(self, event: QPaintEvent): painter = QPainter(self) painter.drawImage(self.rect(), self.image) if self.show_frame: painter.save() pen = QPen() pen.setWidth(2) pen.setColor(QColor("black")) painter.setPen(pen) rect = QRect(1, 1, self.width() - 2, self.height() - 2) painter.drawRect(rect) pen.setColor(QColor("white")) painter.setPen(pen) rect = QRect(3, 3, self.width() - 6, self.height() - 6) painter.drawRect(rect) painter.restore() if self.show_arrow: painter.save() triangle = QPolygonF() dist = 4 point1 = QPoint(self.width() - self.triangle_width, 0) size = QSize(20, self.height() // 2) rect = QRect(point1, size) painter.fillRect(rect, QColor("white")) triangle.append(point1 + QPoint(dist, dist)) triangle.append(point1 + QPoint(size.width() - dist, dist)) triangle.append(point1 + QPoint(size.width() // 2, size.height() - dist)) painter.setBrush(Qt.black) painter.drawPolygon(triangle, Qt.WindingFill) painter.restore()
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted. fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None or self._blink_flag: return # Prepare the scaled qpixmap to paint on the widget. if (self._qpix_scaled is None or self._qpix_scaled.size().width() != rect.width()): if self.fmt in ['image/png', 'image/jpeg']: self._qpix_scaled = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': self._qpix_scaled = QPixmap(svg_to_image( self.fig, rect.size())) if self._qpix_scaled is not None: # Paint the image on the widget. qp = QPainter() qp.begin(self) qp.drawPixmap(rect, self._qpix_scaled) qp.end()
def sideSensitiveArea(self, widget, side): widgetRect = widget.rect() if side == ToolWindowManager.TopOf: return QRect( QPoint(widgetRect.left(), widgetRect.top() - self.borderSensitivity), QSize(widgetRect.width(), self.borderSensitivity * 2)) elif side == ToolWindowManager.LeftOf: return QRect( QPoint(widgetRect.left() - self.borderSensitivity, widgetRect.top()), QSize(self.borderSensitivity * 2, widgetRect.height())) elif side == ToolWindowManager.BottomOf: return QRect( QPoint( widgetRect.left(), widgetRect.top() + widgetRect.height() - self.borderSensitivity), QSize(widgetRect.width(), self.borderSensitivity * 2)) elif side == ToolWindowManager.RightOf: return QRect( QPoint( widgetRect.left() + widgetRect.width() - self.borderSensitivity, widgetRect.top()), QSize(self.borderSensitivity * 2, widgetRect.height())) else: qWarning('invalid side') return QRect()
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None: return # Check/update the qpixmap buffer : qpix2paint = None for qpix in self._qpix_buffer: if qpix.size().width() == rect.width(): qpix2paint = qpix break else: if self.fmt in ['image/png', 'image/jpeg']: qpix2paint = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': qpix2paint = QPixmap(svg_to_image(self.fig, rect.size())) self._qpix_buffer.append(qpix2paint) if qpix2paint is not None: # Paint the image on the widget : qp = QPainter() qp.begin(self) qp.drawPixmap(rect, qpix2paint) qp.end()
def initialize(self): if self.parent(): self.setGeometry(QRect(160, 120, 320, 240)) else: self.setFlags( self.flags() | Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint ) baseSize = QSize(640, 480) self.setGeometry(QRect(self.geometry().topLeft(), baseSize)) self.setSizeIncrement(QSize(10, 10)) self.setBaseSize(baseSize) self.setMinimumSize(QSize(240, 160)) self.setMaximumSize(QSize(800, 600)) self.create() self.m_backingStore = QBackingStore(self) self.m_image = QImage(self.geometry().size(), QImage.Format_RGB32) self.m_image.fill( colorTable[self.m_backgroundColorIndex % len(colorTable)].rgba() ) self.m_lastPos = QPoint(-1, -1) self.m_renderTimer = 0
def visualRect(self, index): """visualRect is a pure virtual member function of QAbstractItemView""" if index.row() < 0 or index.row() >= len(self._line_sizes): return QRect() point = QPoint(-self.horizontalOffset(), self._line_offsets[index.row()] - self.verticalOffset()) return QRect(point, self._line_sizes[index.row()])
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) # Prepare the rect on which the image is going to be painted : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) if self.fig is None or self._blink_flag: return # Check/update the qpixmap buffer : qpix2paint = None for qpix in self._qpix_buffer: if qpix.size().width() == rect.width(): qpix2paint = qpix break else: if self.fmt in ['image/png', 'image/jpeg']: qpix2paint = self._qpix_orig.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) elif self.fmt == 'image/svg+xml': qpix2paint = QPixmap(svg_to_image(self.fig, rect.size())) self._qpix_buffer.append(qpix2paint) if qpix2paint is not None: # Paint the image on the widget : qp = QPainter() qp.begin(self) qp.drawPixmap(rect, qpix2paint) qp.end()
def toImage(self, *args): """ .. py:method:: toImage() :noindex: Convert the graphic to a `QImage` All pixels of the image get initialized by 0 ( transparent ) before the graphic is scaled and rendered on it. The format of the image is `QImage.Format_ARGB32_Premultiplied`. The size of the image is the default size ( ceiled to integers ) of the graphic. :return: The graphic as image in default size .. py:method:: toImage(size, [aspectRatioMode=Qt.IgnoreAspectRatio]) :noindex: Convert the graphic to a `QImage` All pixels of the image get initialized by 0 ( transparent ) before the graphic is scaled and rendered on it. The format of the image is `QImage.Format_ARGB32_Premultiplied`. :param QSize size: Size of the image :param `Qt.AspectRatioMode` aspectRatioMode: Aspect ratio how to scale the graphic :return: The graphic as image .. seealso:: :py:meth:`toPixmap()`, :py:meth:`render()` """ if len(args) == 0: if self.isNull(): return QImage() sz = self.defaultSize() w = np.ceil(sz.width()) h = np.ceil(sz.height()) image = QImage(w, h, QImage.Format_ARGB32) image.fill(0) r = QRect(0, 0, sz.width(), sz.height()) painter = QPainter(image) self.render(painter, r, Qt.KeepAspectRatio) painter.end() return image elif len(args) in (1, 2): size = args[0] aspectRatioMode = Qt.IgnoreAspectRatio if len(args) == 2: aspectRatioMode = args[-1] image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(0) r = QRect(0, 0, size.width(), size.height()) painter = QPainter(image) self.render(painter, r, aspectRatioMode) return image
def drawSymbol(self, painter, point_or_rect): """ Draw the symbol into a rectangle The symbol is painted centered and scaled into the target rectangle. It is always painted uncached and the pin point is ignored. This method is primarily intended for drawing a symbol to the legend. :param QPainter painter: Painter :param point_or_rect: Position or target rectangle of the symbol in screen coordinates :type point_or_rect: QPointF or QPoint or QRectF """ if isinstance(point_or_rect, (QPointF, QPoint)): # drawSymbol( QPainter *, const QPointF & ) self.drawSymbols(painter, [point_or_rect]) return # drawSymbol( QPainter *, const QRectF & ) rect = point_or_rect assert isinstance(rect, QRectF) if self.__data.style == QwtSymbol.NoSymbol: return if self.__data.style == QwtSymbol.Graphic: self.__data.graphic.graphic.render(painter, rect, Qt.KeepAspectRatio) elif self.__data.style == QwtSymbol.Path: if self.__data.path.graphic.isNull(): self.__data.path.graphic = qwtPathGraphic( self.__data.path.path, self.__data.pen, self.__data.brush) self.__data.path.graphic.render(painter, rect, Qt.KeepAspectRatio) return elif self.__data.style == QwtSymbol.SvgDocument: if self.__data.svg.renderer is not None: scaledRect = QRectF() sz = QSizeF(self.__data.svg.renderer.viewBoxF().size()) if not sz.isEmpty(): sz.scale(rect.size(), Qt.KeepAspectRatio) scaledRect.setSize(sz) scaledRect.moveCenter(rect.center()) else: scaledRect = rect self.__data.svg.renderer.render(painter, scaledRect) else: br = QRect(self.boundingRect()) ratio = min( [rect.width() / br.width(), rect.height() / br.height()]) painter.save() painter.translate(rect.center()) painter.scale(ratio, ratio) isPinPointEnabled = self.__data.isPinPointEnabled self.__data.isPinPointEnabled = False pos = QPointF() self.renderSymbols(painter, pos, 1) self.__data.isPinPointEnabled = isPinPointEnabled painter.restore()
def paintEvent(self, event): """Draw marker for A/B loop.""" super().paintEvent(event) painter = QPainter(self) if self.pos_loop_a: pos = self.convert_media_pos_to_widget_pos(self.pos_loop_a) self.icon_a.paint(painter, QRect(QPoint(pos, 0), self.icon_size)) if self.pos_loop_b: pos = self.convert_media_pos_to_widget_pos(self.pos_loop_b) self.icon_b.paint(painter, QRect(QPoint(pos, -3), self.icon_size))
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon.""" painter.save() color = options['color'] char = options['char'] color_options = { QIcon.On: { QIcon.Normal: (options['color_on'], options['on']), QIcon.Disabled: (options['color_on_disabled'], options['on_disabled']), QIcon.Active: (options['color_on_active'], options['on_active']), QIcon.Selected: (options['color_on_selected'], options['on_selected']) }, QIcon.Off: { QIcon.Normal: (options['color_off'], options['off']), QIcon.Disabled: (options['color_off_disabled'], options['off_disabled']), QIcon.Active: (options['color_off_active'], options['off_active']), QIcon.Selected: (options['color_off_selected'], options['off_selected']) } } color, char = color_options[state][mode] painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. draw_size = 0.875 * qRound(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()
def get_gauge(self, parent, macros): aux = [] for k, v in macros.items(): aux.append('{}\t{}\n'.format(k, v)) tooltip = ''.join(aux) width = 320 height = 100 frame = QFrame(parent) frame.setGeometry(QRect(10, 10, width, height)) frame.setMinimumSize(width, height) frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) frame.setObjectName("frame") brush = QBrush(QColor(180, 180, 180)) brush.setStyle(Qt.NoBrush) alarmRec = PyDMDrawingRectangle(frame) alarmRec.channel = "ca://{}".format(macros.get('ALARM', None)) alarmRec.setGeometry(QRect(0, 0, width, height)) alarmRec.setToolTip(tooltip) alarmRec.setProperty("alarmSensitiveContent", True) alarmRec.setProperty("brush", brush) alarmRec.setObjectName("alarmRec") # alarmRec.setStyleSheet("margin:5px; border:3px solid rgb(0, 0, 0);") lblName = QLabel(frame) lblName.setGeometry(QRect(width * 0.05, 50, width - width * 0.05, 20)) font = QFont() font.setPointSize(12) lblName.setFont(font) lblName.setAlignment(Qt.AlignCenter) lblName.setText("{}".format(macros.get('DISP', None))) lblName.setObjectName("lblName") lblName.setToolTip(tooltip) lblVal = PyDMLabel(frame) lblVal.setGeometry(QRect(width * 0.05, 10, width - width * 0.05, 30)) font = QFont() font.setPointSize(18) lblVal.setFont(font) lblVal.setToolTip(tooltip) lblVal.setAlignment(Qt.AlignCenter) lblVal.setProperty("showUnits", False) lblVal.setObjectName("lblVal") lblVal.channel = "ca://{}".format(macros.get('PV', None)) lblVal.precisionFromPV = False lblVal.precision = 2 if self.macros.get('FORMAT', '') == 'EXP': lblVal.displayFormat = PyDMLabel.DisplayFormat.Exponential return frame
def get_gauge(self, parent, pv_info: PVInfo): tooltip = "".join( [f"{key}\t{value}\n" for key, value in pv_info.__dict__.items()] ) width = 320 height = 100 frame = QFrame(parent) frame.setGeometry(QRect(10, 10, width, height)) frame.setMinimumSize(width, height) frame.setFrameShape(QFrame.StyledPanel) frame.setFrameShadow(QFrame.Raised) frame.setObjectName("frame") brush = QBrush(QColor(180, 180, 180)) brush.setStyle(Qt.NoBrush) alarmRec = PyDMDrawingRectangle(frame) alarmRec.channel = "ca://{}".format(pv_info.ALARM) alarmRec.setGeometry(QRect(0, 0, width, height)) alarmRec.setToolTip(tooltip) alarmRec.setProperty("alarmSensitiveContent", True) alarmRec.setProperty("brush", brush) alarmRec.setObjectName("alarmRec") # alarmRec.setStyleSheet("margin:5px; border:3px solid rgb(0, 0, 0);") lblName = QLabel(frame) lblName.setGeometry(QRect(width * 0.05, 50, width - width * 0.05, 20)) font = QFont() font.setPointSize(12) lblName.setFont(font) lblName.setAlignment(Qt.AlignCenter) lblName.setText("{}".format(pv_info.DISP)) lblName.setObjectName("lblName") lblName.setToolTip(tooltip) lblVal = PyDMLabel(frame) lblVal.setGeometry(QRect(width * 0.05, 10, width - width * 0.05, 30)) font = QFont() font.setPointSize(18) lblVal.setFont(font) lblVal.setToolTip(tooltip) lblVal.setAlignment(Qt.AlignCenter) lblVal.setProperty("showUnits", False) lblVal.setObjectName("lblVal") lblVal.channel = "ca://{}".format(pv_info.PV) lblVal.precisionFromPV = False lblVal.precision = 2 if self.macros().get("FORMAT", "") == "EXP": lblVal.displayFormat = PyDMLabel.DisplayFormat.Exponential return frame
def calc_position(self, rect: QRect): columns = sum(1 for el in self._item_list if el.widget() and el.widget().isVisible()) if columns == 0: return element_width = rect.width() // columns x = rect.x() for el in self._item_list: if el.widget() and el.widget().isHidden(): continue el.setGeometry(QRect(x, rect.y(), element_width, rect.height())) x += element_width
def paint(self, painter, option: QStyleOptionViewItem, index: QModelIndex) -> None: text = index.data(RealLabelHint) colors = tuple(index.data(RealJobColorHint)) real_status_color = index.data(RealStatusColorHint) painter.save() painter.setRenderHint(QPainter.Antialiasing, False) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, False) border_pen = QPen() border_pen.setColor(QColorConstants.Black) border_pen.setWidth(1) painter.setBrush(QColorConstants.Blue) painter.setPen(border_pen) painter.drawRect(option.rect) margin = 0 if option.state & QStyle.State_Selected: margin = 5 real_status_rect = QRect( option.rect.x() + margin, option.rect.y() + margin, option.rect.width() - (margin * 2), option.rect.height() - (margin * 2), ) painter.setBrush(QColorConstants.Gray) painter.setBrush(real_status_color) painter.drawRect(real_status_rect) job_rect_margin = 10 job_rect = QRect( option.rect.x() + job_rect_margin, option.rect.y() + job_rect_margin, option.rect.width() - (job_rect_margin * 2), option.rect.height() - (job_rect_margin * 2), ) self._paint_inner_grid(painter, job_rect, colors) text_pen = QPen() text_pen.setColor(QColorConstants.Black) painter.setPen(text_pen) painter.drawText(option.rect, Qt.AlignCenter, text) painter.restore()
def doLayout(self, rect, testonly): left, top, right, bottom = self.getContentsMargins() effective = rect.adjusted(+left, +top, -right, -bottom) x = effective.x() y = effective.y() lineheight = 0 for item in self._items: widget = item.widget() hspace = self.horizontalSpacing() if hspace == -1: hspace = widget.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) vspace = self.verticalSpacing() if vspace == -1: vspace = widget.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) nextX = x + item.sizeHint().width() + hspace if nextX - hspace > effective.right() and lineheight > 0: x = effective.x() y = y + lineheight + vspace nextX = x + item.sizeHint().width() + hspace lineheight = 0 if not testonly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = nextX lineheight = max(lineheight, item.sizeHint().height()) return y + lineheight - rect.y() + bottom
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter): """ Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter: QPainter """ rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) if self._native_icons: opt = QStyleOptionViewItem() opt.rect = rect opt.state = (QStyle.State_Active | QStyle.State_Item | QStyle.State_Children) if not collapsed: opt.state |= QStyle.State_Open if mouse_over: opt.state |= (QStyle.State_MouseOver | QStyle.State_Enabled | QStyle.State_Selected) opt.palette.setBrush(QPalette.Window, self.palette().highlight()) opt.rect.translate(-2, 0) self.style().drawPrimitive(QStyle.PE_IndicatorBranch, opt, painter, self) else: index = 0 if not collapsed: index = 2 if mouse_over: index += 1 ima.icon(self._indicators_icons[index]).paint(painter, rect)
def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1155, 853) self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.verticalLayout = QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QWidget() self.tab.setObjectName(_fromUtf8("tab")) self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.verticalLayout.addWidget(self.tabWidget) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QRect(0, 0, 1155, 20)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
def show_overlay(self, target: QWidget) -> DockWidgetArea: ''' Show the drop overlay for the given target widget Parameters ---------- target : QWidget Returns ------- value : DockWidgetArea ''' if self.d.target_widget is target: # Hint: We could update geometry of overlay here. da = self.drop_area_under_cursor() if da != self.d.last_location: self.repaint() self.d.last_location = da return da self.d.target_widget = target self.d.target_rect = QRect() self.d.last_location = DockWidgetArea.invalid # Move it over the target. self.resize(target.size()) top_left = target.mapToGlobal(target.rect().topLeft()) self.move(top_left) self.show() self.d.cross.update_position() self.d.cross.update_overlay_icons() return self.drop_area_under_cursor()
def doLayout(self, rect, testOnly): left, top, right, bottom = self.getContentsMargins() effectiveRect = rect.adjusted(+left, +top, -right, -bottom) x = effectiveRect.x() y = effectiveRect.y() lineHeight = 0 for item in self.__itemlist: wid = item.widget() spaceX = self.__hSpacing if spaceX == -1: spaceX = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) spaceY = self.__vSpacing if spaceY == -1: spaceY = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) nextX = x + item.sizeHint().width() + spaceX if nextX - spaceX > effectiveRect.right() and lineHeight > 0: x = effectiveRect.x() y = y + lineHeight + spaceY nextX = x + item.sizeHint().width() + spaceX lineHeight = 0 if not testOnly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = nextX lineHeight = max(lineHeight, item.sizeHint().height()) return y + lineHeight - effectiveRect.y() + top + bottom
def __init__(self, tileSource, parent=None): """Constructor. Args: tileSource(MapTileSource): Source for loading the tiles. parent(QObject): Parent object, default `None` """ QGraphicsScene.__init__(self, parent=parent) self._zoom = 15 self._tileSource = tileSource self._tileSource.setParent(self) self._tileSource.tileReceived.connect(self.setTilePixmap) tdim = self._tileSource.tileSize() self._emptyTile = QPixmap(tdim, tdim) self._emptyTile.fill(Qt.lightGray) self._tilesRect = QRect() self._tilePixmaps = {} self._tileInDownload = list() self.setSceneRect(0.0, 0.0, 400, 300) self.sceneRectChanged.connect(self.onSceneRectChanged)
def doLayout(self, rect, testOnly): x = rect.x() y = rect.y() lineHeight = 0 for item in self.itemList: wid = item.widget() spaceX = self.spacing() + wid.style().layoutSpacing( QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) spaceY = self.spacing() + wid.style().layoutSpacing( QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) nextX = x + item.sizeHint().width() + spaceX if nextX - spaceX > rect.right() and lineHeight > 0: x = rect.x() y = y + lineHeight + spaceY nextX = x + item.sizeHint().width() + spaceX lineHeight = 0 if not testOnly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = nextX lineHeight = max(lineHeight, item.sizeHint().height()) return y + lineHeight - rect.y()
def __drawVertical(self, widget, option, painter, size, width): # drop between y_pos = option.rect.topLeft().y() if option.rect.height() == 0: # create indicators l_indicator = self.createTriangle(size, attrs.EAST) l_indicator.translate(QPoint(size + (width / 2), y_pos)) r_indicator = self.createTriangle(size, attrs.WEST) r_indicator.translate( QPoint(widget.width() - size - (width / 2), y_pos)) # draw painter.drawPolygon(l_indicator) painter.drawPolygon(r_indicator) painter.drawLine( QPoint(size + (width / 2), y_pos), QPoint(widget.width() - size - (width / 2), y_pos)) # set fill color background_color = QColor(*iColor["rgba_gray_1"]) brush = QBrush(background_color) path = QPainterPath() path.addPolygon(l_indicator) path.addPolygon(r_indicator) painter.fillPath(path, brush) # drop on else: indicator_rect = QRect((width / 2), y_pos, widget.width() - (width / 2), option.rect.height()) painter.drawRoundedRect(indicator_rect, 1, 1)
def paintEvent(self, event): # this puts the line numbers in the margin painter = QPainter(self) painter.fillRect(event.rect(), self.background) block = self.parent.firstVisibleBlock() font = self.parent.font() while block.isValid(): block_num = block.blockNumber() block_top = self.parent.blockBoundingGeometry(block).translated( self.parent.contentOffset()).top() # if the block is not visible stop wasting time if not block.isVisible() or block_top >= event.rect().bottom(): break if block_num == self.parent.textCursor().blockNumber(): font.setBold(True) painter.setFont(font) painter.setPen(self.highlight_color) background = self.highlight_background else: font.setBold(False) painter.setFont(font) painter.setPen(self.color) background = self.background text_rec = QRect(0, block_top, self.width(), self.parent.fontMetrics().height()) painter.fillRect(text_rec, background) painter.drawText(text_rec, Qt.AlignRight, str(block_num + 1)) block = block.next() painter.end() QWidget.paintEvent(self, event)
def do_layout(self, rect, test_only): (left, top, right, bottom) = self.getContentsMargins() effective_rect = rect.adjusted(left, top, -right, -bottom) x = effective_rect.x() y = effective_rect.y() line_height = 0 for item in self.item_list: wid = item.widget() space_x = self.horizontalSpacing() if space_x == -1: space_x = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) space_y = self.verticalSpacing() if space_y == -1: space_y = wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) next_x = x + item.sizeHint().width() + space_x if next_x - space_x > effective_rect.right() and line_height > 0: x = effective_rect.x() y = y + line_height + space_y next_x = x + item.sizeHint().width() + space_x line_height = 0 if not test_only: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = next_x line_height = max(line_height, item.sizeHint().height()) return y + line_height - rect.y() + bottom
def paintEvent(self, event): tic = time.perf_counter() painter = QPainter(self) rect = event.rect() painter.drawImage(rect, self.image, rect) painter.setPen(QColor.fromRgb(255, 0, 0)) #painter.drawPoints(self.clicks) if self.drawBoxes: self.drawBoxes(painter) # Draw the center mark painter.setPen(QColor.fromRgb(255, 0, 0)) painter.drawLine(self.center.x() - 20, self.center.y(), self.center.x() + 20, self.center.y()) painter.drawLine(self.center.x(), self.center.y() - 20, self.center.x(), self.center.y() + 20) # Draw the scale bar if self.scaleBar: painter.setPen(QColor.fromRgb(40, 40, 40)) painter.setFont(QFont("Arial", 30)) scaleRect = QRect(10, 420, 200, 30) painter.drawText(scaleRect, Qt.AlignCenter, "10 nm") pen = painter.pen() pen.setWidth(5) painter.setPen(pen) painter.drawLine(10, 460, 210, 460) toc = time.perf_counter()
def paintEvent(self, event: QPaintEvent): painter = QPainter(self) painter.save() painter.setRenderHint(QPainter.Antialiasing) size = min(self.width(), self.height()) rect = QRect(0, 0, size, size) painter.setBrush(self.background_color) painter.setPen(self.background_color) painter.drawEllipse(rect) painter.setBrush(self.main_color) painter.setPen(self.main_color) factor = self.nominator / self.denominator radius = size / 2 if factor > 0.5: painter.drawChord(rect, 0, 16 * 360 * 0.5) painter.drawChord(rect, 16 * 180, 16 * 360 * (factor - 0.5)) zero_point = QPointF(0, radius) else: painter.drawChord(rect, 0, 16 * 360 * factor) zero_point = QPointF(size, radius) mid_point = QPointF(radius, radius) point = mid_point + QPointF( math.cos(math.pi * (factor * 2)) * radius, -math.sin(math.pi * (factor * 2)) * radius ) polygon = QPolygonF() polygon += mid_point polygon += zero_point polygon += point painter.drawPolygon(polygon) painter.restore()
def fillPixmap(self, widget, pixmap, offset=None): """ Fill a pixmap with the content of a widget In Qt >= 5.0 `QPixmap.fill()` is a nop, in Qt 4.x it is buggy for backgrounds with gradients. Thus `fillPixmap()` offers an alternative implementation. :param QWidget widget: Widget :param QPixmap pixmap: Pixmap to be filled :param QPoint offset: Offset .. seealso:: :py:meth:`QPixmap.fill()` """ if offset is None: offset = QPoint() rect = QRect(offset, pixmap.size()) painter = QPainter(pixmap) painter.translate(-offset) autoFillBrush = widget.palette().brush(widget.backgroundRole()) if not (widget.autoFillBackground() and autoFillBrush.isOpaque()): bg = widget.palette().brush(QPalette.Window) qwtFillRect(widget, painter, rect, bg) if widget.autoFillBackground(): qwtFillRect(widget, painter, rect, autoFillBrush) if widget.testAttribute(Qt.WA_StyledBackground): painter.setClipRegion(QRegion(rect)) opt = QStyleOption() opt.initFrom(widget) widget.style().drawPrimitive(QStyle.PE_Widget, opt, painter, widget)
def doLayout(self, rect, testOnly): x = rect.x() y = rect.y() line_height = 0 for item in self.item_list: wid = item.widget() if wid is not None: space_x = self.spacing() + wid.style().layoutSpacing( QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) space_y = self.spacing() + wid.style().layoutSpacing( QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) next_x = x + item.sizeHint().width() + space_x if next_x - space_x > rect.right() and line_height > 0: x = rect.x() y = y + line_height + space_y next_x = x + item.sizeHint().width() + space_x line_height = 0 if not testOnly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = next_x line_height = max(line_height, item.sizeHint().height()) return y + line_height - rect.y()
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHints(QPainter.Antialiasing) side = min(self.width(), self.height()) painter.scale(side / 32.0, side / 32.0) painter.setPen(Qt.NoPen) if not self.is_pressed: painter.setBrush(self.back_color) else: painter.setBrush( QColor(self.back_color.red() + 30, self.back_color.green() + 30, self.back_color.blue() + 30)) painter.drawRoundedRect(QRect(0, 0, 32, 32), 8, 8) if self.is_checked: check_path = QPainterPath() check_path.moveTo(self.x1) check_path.lineTo(self.x2) check_path.lineTo(self.x3) pen = QPen(self.check_color, self.check_thick, Qt.SolidLine) painter.setPen(pen) painter.drawPath(check_path)
def mouseOverTitlebar(self, x, y): if self.childAt(QPoint(x, y)): return False else: return QRect(self.appLogoLabel.width(), 0, self.width() - self.appLogoLabel.width(), self.height()).contains(QPoint(x, y))
def legendIcon(self, index, size): """ :param int index: Index of the legend entry (ignored as there is only one) :param QSizeF size: Icon size :return: Icon representing the marker on the legend .. seealso:: :py:meth:`qwt.plot.QwtPlotItem.setLegendIconSize()`, :py:meth:`qwt.plot.QwtPlotItem.legendData()` """ if size.isEmpty(): return QwtGraphic() icon = QwtGraphic() icon.setDefaultSize(size) icon.setRenderHint(QwtGraphic.RenderPensUnscaled, True) painter = QPainter(icon) painter.setRenderHint( QPainter.Antialiasing, self.testRenderHint(QwtPlotItem.RenderAntialiased)) if self.__data.style != QwtPlotMarker.NoLine: painter.setPen(self.__data.pen) if self.__data.style in (QwtPlotMarker.HLine, QwtPlotMarker.Cross): y = 0.5 * size.height() painter.drawLine(0.0, y, size.width(), y) if self.__data.style in (QwtPlotMarker.VLine, QwtPlotMarker.Cross): x = 0.5 * size.width() painter.drawLine(x, 0.0, x, size.height()) if self.__data.symbol: r = QRect(0, 0, size.width(), size.height()) self.__data.symbol.drawSymbol(painter, r) return icon
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon""" painter.save() color, char = options['color'], options['char'] if mode == QIcon.Disabled: color = options.get('color_disabled', color) char = options.get('disabled', char) elif mode == QIcon.Active: color = options.get('color_active', color) char = options.get('active', char) elif mode == QIcon.Selected: color = options.get('color_selected', color) char = options.get('selected', char) painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason for not using full-sized glyphs is the negative bearing of # fonts. draw_size = 0.875 * qRound(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()