47 lines
1.7 KiB
Python
47 lines
1.7 KiB
Python
import sys
|
||
from PySide6.QtWidgets import QGraphicsItem
|
||
from PySide6.QtGui import QPainter, QBrush, QPen
|
||
from PySide6.QtCore import QRectF, Qt
|
||
|
||
# 1. 建立一個自訂的 QGraphicsItem 類別來繪製圓形/橢圓
|
||
class CustomCircleItem(QGraphicsItem):
|
||
def __init__(self, x, y, width, height, color=Qt.red, is_circle=False, parent :QGraphicsItem =None):
|
||
super().__init__(parent = parent) # 呼叫父類別的建構子
|
||
# QRectF 定義了橢圓或圓形的邊界框
|
||
self.rect = parent.boundingRect()
|
||
self.rect.setX(self.rect.x() + x)
|
||
self.rect.setY(self.rect.y() + y)
|
||
|
||
self.color = color
|
||
self.is_circle = is_circle # 用於判斷是否繪製正圓
|
||
|
||
# 為了簡化,如果 is_circle 為 True,強制寬高相等
|
||
if is_circle:
|
||
side = max(width, height) # 取較大邊長作為圓的直徑
|
||
self.rect.setWidth(side)
|
||
self.rect.setHeight(side)
|
||
|
||
|
||
|
||
# 必須實作此方法:定義項目的邊界矩形
|
||
def boundingRect(self):
|
||
# 返回定義橢圓或圓形所需空間的矩形
|
||
# 這對於繪圖更新、碰撞偵測和選擇非常重要
|
||
return self.rect
|
||
|
||
# 必須實作此方法:定義如何繪製項目
|
||
def paint(self, painter: QPainter, option, widget=None):
|
||
# 設定畫筆 (邊框)
|
||
pen = QPen(Qt.white) # 使用白色邊框
|
||
pen.setWidth(0)
|
||
painter.setPen(pen)
|
||
|
||
# 設定畫刷 (填充顏色)
|
||
brush = QBrush(self.color)
|
||
painter.setBrush(brush)
|
||
|
||
# 繪製橢圓或圓形
|
||
# drawEllipse(矩形): 在給定的矩形內繪製一個橢圓。
|
||
# 如果矩形的寬高相等,則繪製一個正圓。
|
||
painter.drawEllipse(self.rect)
|