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

Positioning drawtext inside a rectangle



  • Hi I wanted to draw some text inside a rectangle at different position and I ran into a problem. I have a paint function like this

    QRectF MyGraphicsItem::boundingRect() const
    {
        return QRectF(0, 0, 1000, 150);
    }
    
    void MyGraphicsItem::paint(QPainter *painter)
    {
        QPoint pos1(0, 0);
        QPoint pos2(50, 0);
        QPoint pos3(1500, 0);
    
        painter->drawText(pos1, QString("0"));
        painter->drawText(pos2, QString("50"));
        painter->drawText(pos3, QString("1500"));
    }
    

    mainwindow.cpp

        scene = new QGraphicsScene(this);
        myItem= new MyGraphicsItem;
        scene->addItem(myItem);
    
        ui->graphicsView->setScene(scene);
    

    The last Qpooint position of my texts is longer than the width of my qgraphicsview, but my program is not showing a horizontal scroll bar. I tried changing the horizontal sizing policy in the ui but none of them works.


  • Qt Champions 2019

    Where should the scrollbar appear? You're returning a bounding rect smaller than your coordinates for your third string so it will not be visible.



  • @Christian-Ehrlicher said in Positioning drawtext inside a rectangle:

    Where should the scrollbar appear? You're returning a bounding rect smaller than your coordinates for your third string so it will not be visible.

    Thanks, I tried setting the x position of the third Qpoint and the width of the QgraphicsView in the ui to be less than the bounding rectangle, then the scroll bar came out.

    I'm going to populate and draw the Qpoints from a loop so some of the coordinates may be very large, so I should be declaring my bounding rectangle to be larger than that like QRectF(0, 0, 9999, 100)?



  • @lansing
    I'm not sure what you are trying to achieve.
    Normally, I would calculate the correct bounding rect (and ideally cache the result as long as nothing changes, so calls to boundingRect() stay fast)