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 ScalePicture(self): rect = QRectF(self.graphicsItem.pos(), QSizeF( self.pixMap.size())) unity = self.graphicsView.transform().mapRect(QRectF(0, 0, 1, 1)) width = unity.width() height = unity.height() if width <= 0 or height <= 0: return self.graphicsView.scale(1 / width, 1 / height) viewRect = self.graphicsView.viewport().rect() sceneRect = self.graphicsView.transform().mapRect(rect) if sceneRect.width() <= 0 or sceneRect.height() <= 0: return x_ratio = viewRect.width() / sceneRect.width() y_ratio = viewRect.height() / sceneRect.height() x_ratio = y_ratio = min(x_ratio, y_ratio) self.graphicsView.scale(x_ratio, y_ratio) # if self.readImg.isStripModel: # height2 = self.pixMap.size().height() / 2 # height3 = self.graphicsView.size().height()/2 # height3 = height3/x_ratio # p = self.graphicsItem.pos() # self.graphicsItem.setPos(p.x(), p.y()+height2-height3) self.graphicsView.centerOn(rect.center()) for _ in range(abs(self.scaleCnt)): if self.scaleCnt > 0: self.graphicsView.scale(1.1, 1.1) else: self.graphicsView.scale(1/1.1, 1/1.1)
def export(self, filename=None, add_margin=False): pw = QPdfWriter(filename) dpi = int(QApplication.primaryScreen().logicalDotsPerInch()) pw.setResolution(dpi) pw.setPageMargins(QMarginsF(0, 0, 0, 0)) size = QPageSize(self.getTargetRect().size()) pw.setPageSize(size) painter = QPainter(pw) try: self.setExportMode( True, { 'antialias': True, 'background': self.background, 'painter': painter }) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.LosslessImageRendering, True) source_rect = self.getSourceRect() if add_margin: source_rect.setWidth(source_rect.width() + 25) self.getScene().render(painter, QRectF(self.getTargetRect()), QRectF(source_rect)) finally: self.setExportMode(False) painter.end()
def Recenter(self): itemsRect = QRectF() for item in self._sceneItems: itemsRect = itemsRect.united(item.GraphicsObject().boundingRect().translated(item.GraphicsObject().pos())) self._offset = itemsRect.center() self.UpdateView()
def setText(self, text): self._text = text metrics = QFontMetrics(self._font) self._textRect = QRectF(metrics.boundingRect( QRect(0.0, 0.0, 150.0, 150.0),Qt.AlignLeft, self._text)) self._textRect.translate(5, 5) self.prepareGeometryChange() self._rect = self._textRect.adjusted(-5, -5, 5, 5)
def __init__(self, chart): QGraphicsItem.__init__(self, chart) self._chart = chart self._text = "" self._textRect = QRectF() self._anchor = QPointF() self._font = QFont() self._rect = QRectF()
def boundingRect(self): anchor = self.mapFromParent(self._chart.mapToPosition(self._anchor)) rect = QRectF() rect.setLeft(min(self._rect.left(), anchor.x())) rect.setRight(max(self._rect.right(), anchor.x())) rect.setTop(min(self._rect.top(), anchor.y())) rect.setBottom(max(self._rect.bottom(), anchor.y())) return rect
def _other_areas_at_position(self, qt_local_position: QPointF): result = [] for area in self.world.areas: if "total_boundings" not in area.extra or area == self.area: continue bounds = BoundsFloat.from_bounds(area.extra["total_boundings"]) tl = self.game_loc_to_qt_local([bounds.min_x, bounds.min_y]) br = self.game_loc_to_qt_local([bounds.max_x, bounds.max_y]) rect = QRectF(tl, br) if rect.contains(qt_local_position): result.append(area) return result
def paintEvent(self, event: QPaintEvent): outerRadius = min(self.width(), self.height()) baseRect = QRectF(1, 1, outerRadius - 2, outerRadius - 2) buffer = QImage(outerRadius, outerRadius, QImage.Format_ARGB32_Premultiplied) p = QPainter(buffer) p.setRenderHint(QPainter.Antialiasing) self.rebuildDataBrushIfNeeded() self.drawBackground(p, buffer.rect()) self.drawBase(p, baseRect) if self.m_value > 0: delta = (self.m_max - self.m_min) / (self.m_value - self.m_min) else: delta = 0 self.drawValue(p, baseRect, self.m_value, delta) innerRect, innerRadius = self.calculateInnerRect(outerRadius) self.drawInnerBackground(p, innerRect) self.drawText(p, innerRect, innerRadius, self.m_value) p.end() painter = QPainter(self) painter.fillRect(baseRect, self.palette().window()) painter.drawImage(0, 0, buffer)
def __init__(self, pos=(0, 0), parent=None): super().__init__(parent=parent) self.wx_main = NodeInternal() self.setWidget(self.wx_main) self.setGeometry(QRectF(0, 0, 150, 100)) self.setPos(pos[0], pos[1])
def UpdateView(self): matrix = QTransform() matrix.scale(2 ** self._zoom, 2 ** self._zoom) self.setTransform(matrix) self.setSceneRect(QRectF(self._offset.x(), self._offset.y(), 10, 10)) self.UpdateSelectionBox() self.UpdateHoveredItems()
def update_legend_layout(self): legend = self.chart.legend() rect = QRectF(self.legend_posx.value(), self.legend_posy.value(), self.legend_width.value(), self.legend_height.value()) legend.setGeometry(rect) legend.update()
def calculateInnerRect(self, outerRadius: float): if self.m_barStyle in (self.BarStyle.LINE, self.BarStyle.EXPAND): innerRadius = outerRadius - self.m_outlinePenWidth else: innerRadius = outerRadius * 0.75 delta = (outerRadius - innerRadius) / 2 innerRect = QRectF(delta, delta, innerRadius, innerRadius) return innerRect, innerRadius
def input_to_rect_item(self, input_stream: QDataStream, item: QGraphicsRectItem): self.input_to_shape_item(input_stream, item) # Type rect = QRectF() # Read input_stream >> rect # Set item.setRect(rect)
def cell_rects(self): rect = self.rect() cell_width = rect.width() / self.column_count cell_height = rect.height() / self.row_count for row in range(self.row_count): y = rect.top() + rect.height() * row / self.row_count for column in range(self.column_count): x = rect.left() + rect.width() * column / self.column_count yield QRectF(x, y, cell_width, cell_height)
def resizeEvent(self, event): if self.scene(): self.scene().setSceneRect(QRectF(QPointF(0, 0), event.size())) self._chart.resize(event.size()) self._coordX.setPos(self._chart.size().width() / 2 - 50, self._chart.size().height() - 20) self._coordY.setPos(self._chart.size().width() / 2 + 50, self._chart.size().height() - 20) for callout in self._callouts: callout.updateGeometry() QGraphicsView.resizeEvent(self, event)
def calculate_center_square(self, img_rect) -> QRectF: a = self.QR_SIZE * min(img_rect.height(), img_rect.width()) # Size of square side x = (img_rect.width() - a) / 2 # Position of the square inside rectangle y = (img_rect.height() - a) / 2 if type(img_rect ) != QImage: # if we have a bounding rectangle, not an image x += img_rect.left( ) # then we need to shift our square inside this rectangle y += img_rect.top() return QRectF(x, y, a, a)
def _ShowImg(self, data): self.scaleCnt = 0 self.pixMap = QPixmap() self.pixMap.loadFromData(data) self.show() self.graphicsItem.setPixmap(self.pixMap) self.graphicsView.setSceneRect(QRectF(QPointF(0, 0), QPointF(self.pixMap.width(), self.pixMap.height()))) size = ToolUtil.GetDownloadSize(len(data)) self.sizeLabel.setText(size) weight, height = ToolUtil.GetPictureSize(data) self.resolutionLabel.setText(str(weight) + "x" + str(height)) self.ScalePicture()
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 zoom(self, factor): """缩放 :param factor: 缩放的比例因子 """ _factor = self.graphicsView.transform().scale( factor, factor).mapRect(QRectF(0, 0, 1, 1)).width() if _factor < 0.07 or _factor > 100: # 防止过大过小 return if factor >= 1: self.scaleCnt += 1 else: self.scaleCnt -= 1 self.graphicsView.scale(factor, factor)
def CreateSelectionRect(self) -> QRectF: cursorScene = self.mapToScene(self._currentCursorPosition.toPoint()) if self._state is State.SELECTING: selectionRect = QRectF(0, 0, abs(self._boxSelectionRectAnchor.x() - cursorScene.x()), abs(self._boxSelectionRectAnchor.y() - cursorScene.y())) selectionRect.moveCenter((cursorScene + self._boxSelectionRectAnchor) / 2.0) else: selectionRect = QRectF(cursorScene, QSizeF()) return selectionRect
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 paintEvent(self, event): super(MouseEventMixin, self).paintEvent(event) if not self.__image: return if self.__image.height() == 0 or self.height( ) == 0 or self.__image.width() == 0: return image_aspect_ratio = self.__image.width() / self.__image.height() view_aspect_ratio = self.width() / self.height() if view_aspect_ratio <= image_aspect_ratio: image_height = self.width() / image_aspect_ratio rect = QRectF(0, (self.height() - image_height) / 2, self.width(), image_height) else: image_widh = self.height() * image_aspect_ratio rect = QRectF((self.width() - image_widh) / 2, 0, image_widh, self.height()) painter = QPainter(self.viewport()) painter.drawImage(rect, self.__image) painter.end()
def __init__(self): # Sidebar icons are 28x28 points. Should be at least 56x56 pixels for # HiDPI display compatibility. They will be automatically made theme # aware, so you need only provide a grayscale image, where white is # the color of the shape. icon = QImage(56, 56, QImage.Format_RGB32) icon.fill(0) # Render an "H" as the example icon p = QPainter() p.begin(icon) p.setFont(QFont("Open Sans", 56)) p.setPen(QColor(255, 255, 255, 255)) p.drawText(QRectF(0, 0, 56, 56), Qt.AlignCenter, "H") p.end() SidebarWidgetType.__init__(self, icon, "Hello")
def paintEvent(self, event): super(QtBubbleLabel, self).paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 抗锯齿 rectPath = QPainterPath() # 圆角矩形 height = self.height() - 8 # 往上偏移8 rectPath.addRoundedRect(QRectF(0, 0, self.width(), height), 5, 5) x = self.width() / 5 * 4 # 边框画笔 painter.setPen( QPen(self.BorderColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # 背景画刷 painter.setBrush(self.BackgroundColor) # 绘制形状 painter.drawPath(rectPath)
def drawText(self, p: QPainter, innerRect: QRectF, innerRadius: float, value: float): if not self.m_format: return f = QFont(self.font()) f.setPixelSize(10) fm = QFontMetricsF(f) maxWidth = fm.width(self.valueToText(self.m_max)) delta = innerRadius / maxWidth fontSize = f.pixelSize() * delta * 0.75 f.setPixelSize(int(fontSize)) p.setFont(f) textRect = QRectF(innerRect) p.setPen(self.palette().text().color()) p.drawText(textRect, Qt.AlignCenter, self.valueToText(value))
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, self.antialiased) painter.translate(self.width() / 2, self.height() / 2) for diameter in range(0, 256, 9): delta = abs((self.frameNo % 128) - diameter / 2) alpha = 255 - (delta * delta) / 4 - diameter if alpha > 0: painter.setPen(QPen(QColor(0, diameter / 2, 127, alpha), 3)) if self.floatBased: painter.drawEllipse( QRectF(-diameter / 2.0, -diameter / 2.0, diameter, diameter)) else: painter.drawEllipse( QRect(-diameter / 2, -diameter / 2, diameter, diameter))
def __init__(self): super().__init__() scene = QGraphicsScene() self.setScene(scene) self.setRenderHint(QPainter.Antialiasing) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setMouseTracking(True) self._offset = QPointF(0, 0) self._zoom = 0 self.backgroundColor = QColor(40, 40, 40) self.gridSpacing = QSizeF(60, 60) self.gridThickness = 1 self.gridColor = QColor(100, 100, 100) self.gridZoomThreshold = -1.5 self.showGrid = True self.selectionBoxStrokeColor = QColor(52, 222, 235) self.selectionBoxFillColor = QColor(52, 222, 235, 50) self.selectionBoxThickness = 2 self._editing = True self._hoveredItems: List[ChipItem] = [] self._selectedItems: List[ChipItem] = [] self._sceneItems: Set[ChipItem] = set() self._boxSelectionRectAnchor = QPointF() self._currentCursorPosition = QPointF() self.selectionBox = self.scene().addRect(QRectF(), QPen(self.selectionBoxStrokeColor, self.selectionBoxThickness), QBrush(self.selectionBoxFillColor)) self.selectionBox.setVisible(False) self._state = State.IDLE self.UpdateView()
def drawBase(self, p: QPainter, baseRect: QRectF): if self.m_barStyle == self.BarStyle.DONUT: p.setPen( QPen(self.palette().shadow().color(), self.m_outlinePenWidth)) p.setBrush(self.palette().base()) p.drawEllipse(baseRect) elif self.m_barStyle == self.BarStyle.LINE: p.setPen( QPen(self.palette().base().color(), self.m_outlinePenWidth)) p.setBrush(Qt.NoBrush) p.drawEllipse( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2)) elif self.m_barStyle in (self.BarStyle.PIE, self.BarStyle.EXPAND): p.setPen( QPen(self.palette().base().color(), self.m_outlinePenWidth)) p.setBrush(self.palette().base()) p.drawEllipse(baseRect)
def drawValue(self, p: QPainter, baseRect: QRectF, value: float, delta: float): if value == self.m_min: return if self.m_barStyle == self.BarStyle.EXPAND: p.setBrush(self.palette().highlight()) p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth)) radius = (baseRect.height() / 2) / delta p.drawEllipse(baseRect.center(), radius, radius) return elif self.m_barStyle == self.BarStyle.LINE: p.setPen( QPen(self.palette().highlight().color(), self.m_dataPenWidth)) p.setBrush(Qt.NoBrush) if value == self.m_max: p.drawEllipse( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2)) else: arcLength = 360 / delta p.drawArc( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2), int(self.m_nullPosition * 16), int(-arcLength * 16)) return dataPath = QPainterPath() dataPath.setFillRule(Qt.WindingFill) if value == self.m_max: dataPath.addEllipse(baseRect) else: arcLength = 360 / delta dataPath.moveTo(baseRect.center()) dataPath.arcTo(baseRect, self.m_nullPosition, -arcLength) dataPath.lineTo(baseRect.center()) p.setBrush(self.palette().highlight()) p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth)) p.drawPath(dataPath)