通常情况下,这些事情可以通过边界矩形或形状函数来处理,尝试重载它们。请查看Qt帮助中QGraphicsItem的shape部分(
https://doc.qt.io/qt-6/qgraphicsitem.html#shape)。
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().
所以基本上发生的情况是,所有想要访问与项目相关联的“区域”的函数都会调用shape,然后使用生成的painterpath进行包含或碰撞检测。
因此,如果您有小物品,应该扩大形状区域。
例如,让我们考虑一个线条作为您的目标,那么您的形状实现可能如下所示:
QPainterPath Segment::shape() const{
QLineF temp(qLineF(scaled(Plotable::cScaleFactor)));
QPolygonF poly;
temp.translate(0,pen.widthF()/2.0);
poly.push_back(temp.p1());
poly.push_back(temp.p2());
temp.translate(0,-pen.widthF());
poly.push_back(temp.p2());
poly.push_back(temp.p1());
QPainterPath path;
path.addPolygon(poly);
return path;
}
笔是段落的一部分,我使用它的宽度来扩大形状区域。但你也可以选择其他与你物体的实际尺寸有良好关联的东西。