Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Multi-line Elided text

Multi-line Elided text

Scheduled Pinned Locked Moved General and Desktop
2 Posts 1 Posters 7.2k Views
  • 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 Offline
    O Offline
    omer_saleem
    wrote on last edited by
    #1

    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
    0
    • O Offline
      O Offline
      omer_saleem
      wrote on last edited by
      #2

      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
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved