如何设置 QGraphicsItemGroup 的显示范围?

How can I set the display range of a QGraphicItemGroup?

我有一个 QGraphicsItemGroup 聚合了几个子项,我只想显示组的一部分。(不是子项的数量、区域)。就像这里的图片一样。

我要显示显示区域

为此,我尝试覆盖 QGraphicsItemGroup::boundingRect()。然而,什么也没有发生。我在 QT 文档中找到了这个,也许这就是为什么不起作用的原因。

QGraphicsItemGroup的boundingRect()函数returnsitem组中所有item的外接矩形

此外,我知道我可以更改 QGraphicsView 的大小以使其正常工作。但是我把View作为CentralWidget,因为我还需要在View中显示其他对象,我不能改变View的大小。

如何设置QGraphicItemGroup的显示范围?

要执行此任务,我们可以通过返回定义可见区域的 QPainterPath 来覆盖 shape(),以便它传播到其子项,我们启用标志 ItemClipsChildrenToShape:

class GraphicsItemGroup: public QGraphicsItemGroup{
public:
    GraphicsItemGroup(QGraphicsItem * parent = 0):QGraphicsItemGroup(parent){
        setFlag(QGraphicsItem::ItemClipsChildrenToShape, true);
    }
    QPainterPath shape() const
    {
        if(mShape.isEmpty())
            return QGraphicsItemGroup::shape();
        return mShape;
    }
    void setShape(const QPainterPath &shape){
        mShape = shape;
        update();
    }

private:
    QPainterPath mShape;
};

示例:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    w.setLayout(new QVBoxLayout);

    QGraphicsView view;
    QPushButton button("click me");

    w.layout()->addWidget(&view);
    w.layout()->addWidget(&button);

    view.setScene(new QGraphicsScene);
    GraphicsItemGroup group;
    view.scene()->addItem(&group);
    auto ellipse = new QGraphicsEllipseItem(QRectF(0, 0, 100, 100));
    ellipse->setBrush(Qt::red);
    auto rect = new QGraphicsRectItem(QRect(150, 150, 100, 100));
    rect->setBrush(Qt::blue);
    group.addToGroup(ellipse);
    group.addToGroup(rect);

    QObject::connect(&button, &QPushButton::clicked, [&group](){
        QPainterPath shape;
        if(group.shape().boundingRect() == group.boundingRect()){
            shape.addRect(0, 50, 250, 150);
        }
        group.setShape(shape);
    });

    w.show();
    return a.exec();
}

输出:

完整的例子可以在下面link.

中找到