Important: Please read the Qt Code of Conduct -

Limit Qstring in QrectF

  • hi, i am drawing rectangle on an item and i want to draw text inside the rectangle, but the text is coming out of the box, how can i put my text inside the rectangle(inside bounding rect of item) and below is the code .

    @void CBirdsEyeItem::paint(QPainter* f_painter, const QStyleOptionGraphicsItem* f_styleItem, QWidget* f_widget)
    IBaseReferenceDataItem::paint(f_painter,f_styleItem, f_widget); bq. here i am drawing rectngle

    const qreal l_lod = f_styleItem->levelOfDetailFromTransform(f_painter->worldTransform());

    if(getPolygon().size() > 4)
    QPointF l_idPnt = getPolygon().boundingRect().center(); bq. this will give center point of my item

    if(l_lod > 5.0)
    QFont font("Times", 1);
    f_painter->drawText(l_idPnt, getId());

  • @QFont font("times", 24);
    QFontMetrics fm(font);
    int pixelsWide = fm.width("What's the width of this text?");
    int pixelsHigh = fm.height();@

    Ref: QFontMatrics

  • Set the flag QGraphicsItem::ItemClipsToShape for your item.

  • hi Asperamanca,
    this flag will clip the data, so i will lost data, i don't want that and i want my text to be fit in the item .

  • In this case, you should go with Rahul's code provided above. Make the item large enough to fit the text.

  • in my case, i should not change item size, item size is fixed here and text length is dynamic, i have to show may entire text(varible length text) on fixed size item .

  • hi Rahul Das, could you please tell me how it will be useful for my situation ..

  • bq. how can i put my text inside the rectangle(inside bounding rect of item)

    Well, Obviously you need to resize it. It is your need and logic whether you'll need to wrap the text Or adjust the bounding rect Or Font Size.

    Refer "Char-map example":
    and this old "thread": as well

Log in to reply