Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Qt Academy Launch in California!

    Multi-line Elided text

    General and Desktop
    1
    2
    6692
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • O
      omer_saleem last edited by

      Hi,

      I am trying to write paint routine to draw wrapped text, but with a limit on the number of lines. If the text is still too large is elides the last line. The effect I'm looking for is like:

      This is some example
      text that is too big to...

      I can get single line to work fine but can't seem to make it work with multi-line. I saw a similar query regarding the same use case in QML elsewhere is the forum, but am specifically querying its use with standard paint method using QPainter.

      Most appreciated!

      1 Reply Last reply Reply Quote 0
      • O
        omer_saleem last edited by

        Ok, I have worked out a work-around, not the prettiest solution but it works...

        Basically, the code uses the QTextLayout to calculate the (natural) lengths of each line and adds them up and does this for n-1 lines. For the last line it simply adds the full width available and then creates an elided string with all the widths as if they were intended to be on one long line. Then the painter simply draw the text with word wrapping.

        @
        QTextLayout textLayout(text);
        textLayout.setFont(font);
        int widthUsed = 0;
        int lineCount = 0;
        textLayout.beginLayout();

        while (++lineCount < LINE_LIMIT) {
            QTextLine line = textLayout.createLine();
            if (!line.isValid())
                break;
        
            line.setLineWidth(availableWidth);
            widthUsed += line.naturalTextWidth();
        }
        textLayout.endLayout();
        
        widthUsed += availableWidth;
        
        QString newText = painter->fontMetrics().elidedText(text, Qt::ElideRight, widthUsed);
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, newText);
        

        @

        1 Reply Last reply Reply Quote 0
        • First post
          Last post