gpt4 book ai didi

c++ - 如何设置 QGraphicsItemGroup 的显示范围?

转载 作者:太空宇宙 更新时间:2023-11-04 12:53:08 39 4
gpt4 key购买 nike

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

Image is here!

我要显示显示区域。

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

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

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

如何设置QGraphicItemGroup的显示范围?

最佳答案

要执行此任务,我们可以通过返回定义可见区域的 QPainterPath 来覆盖 shape(),以便它传播到它的 child 我们启用标志 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中找到.

关于c++ - 如何设置 QGraphicsItemGroup 的显示范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972795/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com