可以通过重新实现QGraphicsItem::shape()
函数来实现只能选中外框的图形。
示例代码如下:
class MyItem : public QGraphicsItem
{
public:
QRectF boundingRect() const {
return QRectF(0, 0, 100, 100);
}
QPainterPath shape() const {
QPainterPath path;
path.addRect(boundingRect());
return path;
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
painter->drawRect(boundingRect());
}
};
在上述代码中,我们重新实现了shape()
函数,返回一个矩形路径,表示这个图形的边界。然后在paint()
函数中使用drawRect()
函数绘制矩形框。
使用这个自定义的图形项时,只需要将它添加到场景中即可:
MyItem *item = new MyItem();
scene->addItem(item);
现在,你可以选择这个图形项,但只有矩形框会被高亮显示。