Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How do I position QGraphicsItem rectangle to the top left of my QGraphicsView?



  • I have created a QGraphicsView in designer and a custom QGraphicsItem. I want to have my item to be the same width as the view and position begin from the top left corner of the view.

    My view size was set to have width=1000px and height=120px, and my item is height=50px. I ran into a problem with my item positioned vertically in the center of my view and I don't know how to move to the the top left corner.

    my_app.cpp

    my_app constructor() {
        myScene = new QGraphicsScene(this);
        m_ui.myView->setScene(myScene );
        myItem = new MyQGraphicsItem();
    }
    
    void run_app() {
        myItem->setViewWidth(m_ui.myView->width());
        myScene->addItem(myItem);
    }
    
    

    MyQGraphicsItem.cpp

    QRectF MyQGraphicsItem::boundingRect() const
    {    
        return QRectF(0, 0, m_viewWidth, 50);
    }
    
    void MyQGraphicsItem::setViewWidth(int a_viewWidth)
    {
        m_viewWidth = a_viewWidth;
    }
    

    I tried changing the x and y arguments in the boundingRect but the item always stays vertically in the center of the view.


  • Lifetime Qt Champion

    Hi,

    You should likely call setPos on your objects.


Log in to reply