How to get the QRect size of MultiLine QString text that need display in multiple line?



  • I have a long QString text need to display in multiple-line,so I use QFontMetrics::boundingRect to calculate the QRect size ,because my text is long so that I used Qt::TextWordWrap ,but the rect size returned is only the single-line,so what is the wrong ?My code is underline.Thanks!

    QPainter painter(this);
    QString text("1234567890123456789012345678901234567890"
                 "1234567890123456789012345678901234567890"
                 "1234567890123456789012345678901234567890"
                 "1234567890123456789012345678901234567890");
    int width = this->width()-40;
    int flags = Qt::TextWordWrap;
    qDebug()<<"font:"<<painter.font().pointSize()<<",pixelSize="<<painter.font().pixelSize();
    
    QFontMetrics metrics = painter.fontMetrics();
    QRect textBoundingRect = metrics.boundingRect(QRect(0,0,width,0),flags,text);
    painter.translate(20,20);
    painter.drawRect(textBoundingRect);
    painter.drawText(textBoundingRect,Qt::TextWordWrap,text);


  • @vitasr 您好!

    相同类型的问题,发布一个即可。 随后,可以手动合并,删除一个。这个我就不替你修改。

    原因已经在上一个帖子说明了,这里说下我的方法,仅供参考;

    1. 查分QString 为多个子串。split即可;
    2. 分别计算每个子串的QRect;
    3. 合并QRect=> QRect QRect::united(const QRect &rectangle) const

    希望对您有所帮助。


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.