如何在PyQt6中从中心绘制矩形?

问题描述 投票:0回答:1

我想从它的中心画一个矩形,如下图所示。

矩形图像:

the image of rectangle

painter.rectMode(Center)
painter.drawRect(x, y, w, h)

我怎样才能完成这项任务?

我想从中心画一个矩形。 请帮助我。

python pyqt draw paint
1个回答
0
投票

这是一个简单的几何演算,可以通过简单的函数来处理

from PyQt6.QtGui import QPaintEvent, QPainter, QPen, QBrush, QColor
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtCore import Qt
from sys import argv, exit


class Window(QWidget):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.screen_width = 1920
        self.screen_height = 1080
        self.window_width = 700
        self.window_height = 400
        self.setGeometry(
            (self.screen_width - self.window_width) // 2,
            (self.screen_height - self.window_height) // 2,
            self.window_width,
            self.window_height,
        )
        self.show()

    def drawRectFromCenter(self, x, y, w, h):
        return x - w // 2, y - h // 2, w, h

    def paintEvent(self, a0: QPaintEvent | None) -> None:
        painter = QPainter()
        painter.begin(self)
        painter.setPen(QPen(QColor(0, 0, 0), 0, Qt.PenStyle.SolidLine))
        # draw rectangle from top-left corner
        x_from_top_left = 100
        y_from_top_left = 100
        w_from_top_left = 200
        h_from_top_left = 200
        r_from_top_left = 10
        painter.setBrush(QBrush(QColor(0, 255, 0), Qt.BrushStyle.SolidPattern))
        painter.drawRect(
            x_from_top_left, y_from_top_left, w_from_top_left, h_from_top_left
        )
        painter.setBrush(QBrush(QColor(255, 0, 0, 128), Qt.BrushStyle.SolidPattern))
        painter.drawEllipse(
            x_from_top_left - r_from_top_left // 2,
            y_from_top_left - r_from_top_left // 2,
            r_from_top_left,
            r_from_top_left,
        )
        # draw rectangle from center
        x_from_center = 500
        y_from_center = 200
        w_from_center = 200
        h_from_center = 200
        r_from_center = 10
        painter.setBrush(QBrush(QColor(0, 255, 0), Qt.BrushStyle.SolidPattern))
        x, y, w, h = self.drawRectFromCenter(
            x_from_center, y_from_center, w_from_center, h_from_center
        )
        painter.drawRect(x, y, w, h)
        painter.setBrush(QBrush(QColor(255, 0, 0, 128), Qt.BrushStyle.SolidPattern))
        painter.drawEllipse(
            x_from_center - r_from_center // 2,
            y_from_center - r_from_center // 2,
            r_from_center,
            r_from_center,
        )
        return super().paintEvent(a0)


if __name__ == "__main__":
    App = QApplication(argv)
    window = Window()
    exit(App.exec())

窗口看起来像这样。

The window.

© www.soinside.com 2019 - 2024. All rights reserved.