|
|
|
from PySide6.QtCore import Qt, QRectF, Signal, QObject
|
|
|
|
from PySide6.QtGui import QPainter, QPen, QColor, QFontMetricsF, QPainterPath
|
|
|
|
from PySide6.QtWidgets import QGraphicsItem
|
|
|
|
|
|
|
|
|
|
|
|
class RoundedRectangleItem(QGraphicsItem, QObject):
|
|
|
|
selected = Signal(int)
|
|
|
|
unselected = Signal(int)
|
|
|
|
|
|
|
|
def __init__(self, x, y, text, id):
|
|
|
|
QGraphicsItem.__init__(self)
|
|
|
|
QObject.__init__(self)
|
|
|
|
self.rect = QRectF(x, y, 70, 70)
|
|
|
|
self.radius = 10
|
|
|
|
self.text = text
|
|
|
|
self.id = id
|
|
|
|
self.isSelected = False # 是否被选中
|
|
|
|
|
|
|
|
def boundingRect(self):
|
|
|
|
return self.rect
|
|
|
|
|
|
|
|
def shape(self):
|
|
|
|
path = QPainterPath()
|
|
|
|
path.addRoundedRect(self.rect, self.radius, self.radius)
|
|
|
|
return path
|
|
|
|
|
|
|
|
def paint(self, painter, option, widget):
|
|
|
|
painter.setRenderHint(QPainter.Antialiasing) # 设置抗锯齿
|
|
|
|
pen = QPen(Qt.black)
|
|
|
|
painter.setPen(pen)
|
|
|
|
|
|
|
|
if self.isSelected:
|
|
|
|
# 如果被选中,设置不同的填充颜色和边框样式
|
|
|
|
painter.setBrush(QColor(255, 0, 0, 255)) # 设置选中时的填充颜色
|
|
|
|
pen.setWidth(2) # 设置边框宽度
|
|
|
|
pen.setStyle(Qt.DashLine) # 设置虚线边框样式
|
|
|
|
painter.setPen(pen)
|
|
|
|
else:
|
|
|
|
painter.setBrush(QColor(0, 255, 0, 255)) # 设置默认的填充颜色
|
|
|
|
|
|
|
|
# 绘制圆角矩形
|
|
|
|
painter.drawRoundedRect(self.rect, self.radius, self.radius)
|
|
|
|
|
|
|
|
# 计算文本的位置
|
|
|
|
font = painter.font()
|
|
|
|
font.setPointSize(36)
|
|
|
|
painter.setFont(font)
|
|
|
|
metrics = QFontMetricsF(font)
|
|
|
|
text_bounding_rect = metrics.boundingRect(str(self.text))
|
|
|
|
text_width = text_bounding_rect.width()
|
|
|
|
text_height = text_bounding_rect.height()
|
|
|
|
text_x = self.rect.center().x() - text_width / 2
|
|
|
|
text_y = self.rect.center().y() + text_height / 4
|
|
|
|
|
|
|
|
# 绘制文本
|
|
|
|
painter.drawText(text_x, text_y, str(self.text))
|
|
|
|
|
|
|
|
def mousePressEvent(self, event):
|
|
|
|
# 鼠标点击时切换选中状态
|
|
|
|
self.isSelected = not self.isSelected
|
|
|
|
self.update()
|
|
|
|
|
|
|
|
# 发射选中信号
|
|
|
|
if self.isSelected:
|
|
|
|
self.selected.emit(self.id)
|
|
|
|
else:
|
|
|
|
self.unselected.emit(self.id)
|
|
|
|
|
|
|
|
super().mousePressEvent(event)
|