代码之家  ›  专栏  ›  技术社区  ›  Ryou

如何设置QGraphicItemGroup的显示范围?

  •  1
  • Ryou  · 技术社区  · 8 年前

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

    Image is here!

    我想显示显示区域。

    为此,我尝试了重写QGraphicsSiteMgroup::boundingRect()。然而,什么都没有发生。我在QT文档中发现了这一点,也许这就是为什么不起作用的原因。

    QGraphicsItemGroup的boundingRect()函数返回项目组中所有项目的边框。

    此外,我知道我可以更改QGraphicsView的大小以使其正常工作。但是,我将视图放置为CentralWidget,因为我还需要在视图中显示其他对象,所以我无法更改视图的大小。

    如何设置QGraphicItemGroup的显示范围?

    1 回复  |  直到 7 年前
        1
  •  0
  •   eyllanesc    8 年前

    要执行此任务,我们可以覆盖 shape() 通过返回 QPainterPath 它定义了可见区域,以便将其传播到其子级,我们启用该标志 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();
    }
    

    输出:

    enter image description here

    enter image description here

    下面是完整的示例 link .