自定义 QGraphicsItem

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

QGraphicsItem 是场景中 item 的基类。图形视图提供了一些典型形状的标准 item,例如:矩形 ( QGraphicsRectItem )、椭圆 ( QGraphicsEllipseItem ) 、文本项 ( QGraphicsTextItem )。

当这些不满足需求时(例如:在一些复杂的工作流场景中),往往需要自定义,通常的做法就是继承 QGraphicsItem。

自定义 QGraphicsItem

要实现自定义 item,需要覆盖 QGraphicsItem 的两个纯虚函数:

  • void paint()
  • 以本地坐标绘制 item 的内容
  • QRectF boundingRect()
  • 将 item 的外边界作为矩形返回
  • 由 QGraphicsView 调用以确定什么区域需要重绘

除此之外,可能还需要附加其他需求,例如:

  • QPainterPath shape() - item 的形状
  • 由 contains() 和 collidesWithPath() 用于碰撞检测
  • 如果未实现,则默认为 boundingRect()
  • 使用信号/槽、属性机制:继承 QObject 和 QGraphicsItem(或直接继承 QGraphicsObject)
  • 处理鼠标事件:重新实现 mouse***Even
  • 19
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
自定义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的基础,您可以使用更复杂的绘图和交互技术来实现更高级的图形元素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一去丶二三里

有收获,再打赏!

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

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

打赏作者

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

抵扣说明:

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

余额充值