Home > OS >  How to use the QGraphicsItem::setPos() function
How to use the QGraphicsItem::setPos() function

Time:09-22

I can't figure out how the setPos() function of the QGraphicsItem class works.

My Rect class has no parent, so its origin is relative to the scene.

I try to put the rectangle back at (0, 0) after it is moved with the mouse but it is placed in a different place depending on where I had moved it. I suppose that means that the origin of the scene moves but what causes this change?

class Rect : public QGraphicsItem {
public:
    Rect(): QGraphicsItem()
    {
        setFlag(ItemIsMovable);
    }

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        painter->drawRect(0, 0, 20, 20);
    }

    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
    {
            setPos(0, 0);
            update();
            QGraphicsItem::mouseReleaseEvent(event);
    }

    QRectF boundingRect() const
    {
            return QRectF(0, 0, 20, 20);
    }

private:
};
int main(int argc, char *argv[])
{
        QApplication a(argc, argv);
        QGraphicsScene scene;
        QGraphicsView view(&scene);
        Rect obj;
        scene.addItem(&obj);

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

CodePudding user response:

When you create a QGraphicsView you initially accept the default settings. A standard setting is, for example, that it is horizontally centered.

enter image description here

Another factor is that the default area size is probably up to the maximum size.

what you can do set a custom size for the scene. You do that with graphicsView->setSceneRect(0,0,300,300); (for example)

    scene       = new QGraphicsScene(this);
    
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView->setSceneRect(0,0, 300,300);
    
    rectItem    = new QGraphicsRectItem(0,0, 100, 100);
    rectItem->setPen(QPen(Qt::darkMagenta, 2));
    rectItem->setBrush(QGradient(QGradient::SaintPetersburg));
    rectItem->setPos(190,10);

    scene->addItem(rectItem);

enter image description here enter image description here

So in summary: if you want to work with fixed values. maybe it is better to know the total size. (that was not clear from your code, that's why I gave this example)

  • Related