Multi-line Elided text



  • 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!



  • 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);
    

    @


Log in to reply
 

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