自定义 QGraphicsItem 选中样式

在Qt图形视图中,当选中QGraphicsItem时默认显示边框虚线,本文介绍了虚线的由来,并提供了如何去除虚线以及自定义选中样式的详细步骤,通过修改源码实现选中时边框变为黄色虚线。
摘要由CSDN通过智能技术生成

作者: 一去、二三里
个人微信号: iwaleon
微信公众号: 高效程序员

在 Scene 中添加 QGraphicsItem 后,当选中该 item 时,会看到边缘区域出现虚线,感觉不太美观。下面,我们来讲解如何去掉虚线并自定义选中样式。

默认样式

以椭圆为例,其它如:矩形、多边形等 item 类似。

// 构建一个椭圆
QGraphicsEllipseItem *pItem = new QGraphicsEllipseItem();
// 设置可选中、可移动
pItem->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);

// 设置样式(画笔 - 边框色 画刷 - 背景色)
QPen pen = pItem->pen();
pen.setWidth(2);
pen.setColor(QColor(0, 160, 230));
pItem->setPen(pen);
pItem->setBrush(QColor(247, 160, 57));
// ......

要出现选中效果,需

自定义QGraphicsItem,可以继承QGraphicsItem类,并在派生类中实现paint()和boundingRect()函数。 paint()函数用于绘制图形元素,您可以使用QPainter类绘制自己的形状、文本、图像等。boundingRect()函数返回该图形元素的边界矩形,它用于定义该图形元素的碰撞检测区域。 以下是一个简单的例子: ```python from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class CustomItem(QGraphicsItem): def __init__(self, parent=None): super().__init__(parent) def boundingRect(self): return QRectF(-50, -50, 100, 100) def paint(self, painter, option, widget): painter.setBrush(QColor(255, 0, 0)) painter.drawEllipse(-50, -50, 100, 100) ``` 在这个例子中,我们继承了QGraphicsItem类,并实现了boundingRect()和paint()函数。boundingRect()函数返回一个100x100的矩形,paint()函数绘制了一个红色的圆形。 然后,您可以将这个自定义图形元素添加到 QGraphicsScene 中,并在 QGraphicsView 中显示它: ```python from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class CustomItem(QGraphicsItem): def __init__(self, parent=None): super().__init__(parent) def boundingRect(self): return QRectF(-50, -50, 100, 100) def paint(self, painter, option, widget): painter.setBrush(QColor(255, 0, 0)) painter.drawEllipse(-50, -50, 100, 100) if __name__ == '__main__': app = QApplication([]) scene = QGraphicsScene() item = CustomItem() scene.addItem(item) view = QGraphicsView(scene) view.show() app.exec_() ``` 这个例子创建了一个 QGraphicsScene,然后创建了一个CustomItem对象,并将其添加到场景中。最后,创建了一个 QGraphicsView 对象,并将场景设置为其父级。运行这个程序,您将看到一个红色圆形在视图中心。 这只是自定义QGraphicsItem的基础,您可以使用更复杂的绘图和交互技术来实现更高级的图形元素。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一去丶二三里

有收获,再打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值