QGraphicsItem设置绘图区域和鼠标响应以及碰撞检测区域,并实现碰撞检测
QGraphicsItem中有兩個方法,分別用來控制QGraphicsItem的繪圖區(qū)域和碰撞檢測區(qū)域:
1.[pure virtual] QRectF QGraphicsItem::boundingRect() const
官方文檔解釋如下:
This pure virtual function defines the outer bounds of the item as a rectangle; all painting must be restricted to inside an item’s bounding rect. QGraphicsView uses this to determine whether the item requires redrawing.
Although the item’s shape can be arbitrary, the bounding rect is always rectangular, and it is unaffected by the items’ transformation.
If you want to change the item’s bounding rectangle, you must first call prepareGeometryChange(). This notifies the scene of the imminent change, so that it can update its item geometry index; otherwise, the scene will be unaware of the item’s new geometry, and the results are undefined (typically, rendering artifacts are left within the view).
Reimplement this function to let QGraphicsView determine what parts of the widget, if any, need to be redrawn.
Note: For shapes that paint an outline / stroke, it is important to include half the pen width in the bounding rect. It is not necessary to compensate for antialiasing, though.
Example:
QRectF CircleItem::boundingRect() const
{
qreal penWidth = 1;
return QRectF(-radius - penWidth / 2, -radius - penWidth / 2,
diameter + penWidth, diameter + penWidth);
}
簡單來說,通過在繼承自QGraphicsItem的子類中重寫boundingRect()方法就可以自定義item的繪圖區(qū)域,QGraphicsView 會根據boundingRect()來確定哪些區(qū)域需要重繪。
2.[virtual] QPainterPath QGraphicsItem::shape() const
Returns the shape of this item as a QPainterPath in local coordinates. The shape is used for many things, including collision detection, hit tests, and for the QGraphicsScene::items() functions.
The default implementation calls boundingRect() to return a simple rectangular shape, but subclasses can reimplement this function to return a more accurate shape for non-rectangular items. For example, a round item may choose to return an elliptic shape for better collision detection. For example:
QPainterPath RoundItem::shape() const
{
QPainterPath path;
path.addEllipse(boundingRect());
return path;
}
The outline of a shape can vary depending on the width and style of the pen used when drawing. If you want to include this outline in the item’s shape, you can create a shape from the stroke using QPainterPathStroker.
This function is called by the default implementations of contains() and collidesWithPath().
簡單來說這個方法主要用來控制鼠標響應以及碰撞檢測區(qū)域。
我通過這兩個方法實現了如下碰撞檢測效果:
我的碰撞檢測代碼如下:
總結
以上是生活随笔為你收集整理的QGraphicsItem设置绘图区域和鼠标响应以及碰撞检测区域,并实现碰撞检测的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中ExpandableLi
- 下一篇: 你知道不注册国外邮箱也能往国外发邮件吗?