PDA

View Full Version : change rect of parent when child's boundingrect is changed or new child is added



mvbhavsar
20th April 2017, 09:31
Hi,

I want to implement grid using qgraphicsrectitem in which each cell can has multiple child and grandchildren. i.e. I have outer rectangle R1 with rect as R(0,0,300,300). This rect will have 3 child qgraphicsrectitem as RC1(0,0,300,100), RC2(0,100,300,100), RC3(0,200,300,100)
when I will add 2 children in RC1 as RGC1(0,0,300,75) and RGC1(0,75,300,75), it should change bounding rect as belows.

RGC1 - (0,0,300,75)
RGC2 - (0,75,300,75)
RC1 - (0,0,300,150),
RC2 - (0,150,300,100)
RC3 - (0,250,300,100)
R - (0,0,300,250)

This means basically, I want to implement that if child is added or resized all its parents and super parents to get re-shaped so that all children remain inside the bounding rect of parent and will not be out of border.

Any idea for this

Manish

Santosh Reddy
20th April 2017, 12:44
#include <QtWidgets>

class GraphicsRectItem : public QGraphicsRectItem
{
public:
explicit GraphicsRectItem(const QString & name, QGraphicsItem * parent = 0)
: QGraphicsRectItem(parent)
, text(new QGraphicsSimpleTextItem(this))
{
setData(0, name);
}

void setSize(const QRect & r)
{
setRect(r);

GraphicsRectItem * parent = dynamic_cast<GraphicsRectItem *>(parentItem());

if(parent)
parent->adjust();

// Showing rect size in text
text->setText(QString("%5-{%1,%2,%3,%4}").arg(r.x()).arg(r.y()).arg(r.width()).arg(r.heigh t()).arg(data(0).toString()));
text->setPos(rect().center());
text->moveBy(-text->boundingRect().width()/2, -text->boundingRect().height()/2);
}

private:
void adjust()
{
QRect rect;

foreach(const QGraphicsItem * child, childItems())
if(dynamic_cast<const GraphicsRectItem *>(child))
rect = rect.united(child->boundingRect().toRect());

setSize(rect);
}

QGraphicsSimpleTextItem * const text;
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

GraphicsRectItem * R = new GraphicsRectItem("R");

GraphicsRectItem * RC1 = new GraphicsRectItem("RC1", R);
GraphicsRectItem * RC2 = new GraphicsRectItem("RC2", R);
GraphicsRectItem * RC3 = new GraphicsRectItem("RC3", R);

GraphicsRectItem * RGC1 = new GraphicsRectItem("RGC1", RC1);
GraphicsRectItem * RGC2 = new GraphicsRectItem("RGC2", RC1);

RGC1->setSize(QRect(0,0,300,75));
RGC2->setSize(QRect(0,75,300,75));

RC2->setSize(QRect(0,150,300,100));
RC3->setSize(QRect(0,250,300,100));

QGraphicsScene scene;
scene.addItem(R);

QGraphicsView view;
view.setScene(&scene);
view.show();

return app.exec();
}