Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt nested QGraphicsItem coordinates

I would expect, from documentation, that this snippet

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QGraphicsView *v = new QGraphicsView(new QGraphicsScene);
    setCentralWidget(v);

    QGraphicsRectItem *r1 = v->scene()->addRect(QRectF(100,100, 200,200), QPen(), QBrush(Qt::red));
    QGraphicsRectItem *r2 = new QGraphicsRectItem(r1);
    r2->setRect(QRectF(10,10, 50,50));
    r2->setBrush(QBrush(Qt::blue));
}

would draw a blue rect inside the red one, instead here is the result:

enter image description here

Do I miss something ?

like image 627
CapelliC Avatar asked Apr 29 '26 12:04

CapelliC


2 Answers

Do I miss something?

Yes.

Calling setRect() on a QGraphicsRectItem does not actually change its pos(), it just changes the position of the rectangle that it draws, but the item's position is unchanged. Thus, your r1 has a pos of (0, 0), but its rectangle is drawn at a (100, 100) offset to its pos().

To avoid confusion, it's usually easier to leave your rect at (0, 0) and call setPos() on your QGraphicsRectItem to move it where you want it.

like image 133
Chris Avatar answered May 01 '26 04:05

Chris


If you wanted the blue rectangle inside the red one, you could either set its rect position in screen coordinates, or set the blue rectangle as the parent of the red rectangle with setParentItem. That way, the child's position is set relative to its parent.

like image 24
TheDarkKnight Avatar answered May 01 '26 03:05

TheDarkKnight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!