Important: Please read the Qt Code of Conduct -

Auto new line in text when overflowing

  • Hi,
    I need to put text from a text file into a specific area in a QImage (see it as a simple rectangle delimited by visible lines). However if the text is too large, then it overflows and that's definitely not the result I want. (Note that I cannot edit the text itself to add line breaks)
    Is there any possibility to "generate" a new line? What I've tried so far:

    • QLabel::setWordWrap (only works if a line break character is present, which is not the case for me
    • drawText with a bounding box

    None of them seem to work for what I'm trying to do.

  • Lifetime Qt Champion


    Can you share a sample code that reproduces this ?

  • Hi, thanks for replying!
    Here is some of the code, this is where everything happens:

    QImage my_template("char456.png");
    QPainter my_painter(&my_template);
    my_painter.drawText(QRect(155, 134, 522, 66), Qt::TextWordWrap, "aeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"); //on purpose

    The template in question is a simple rectangle, like this:

  • Moderators

    Well, without having a breakable space (that's a white space character) the function has no way of knowing where to break the character sequence. Have you tried passing QTextOption::WrapAnywhere to the QPainter::drawText function? I believe it should be working for you, namely:

    QImage image("char.png");
    QPainter painter(&image);
    QString longString = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    QRect envelope(0, 0, image.width(), image.height());
    painter.drawText(envelope, longString, QTextOption::WrapAnywhere);

Log in to reply