Origin: Qt More specifically, this is a trimmed down version on the algorithm in: https://code.woboq.org/qt5/qtbase/src/widgets/styles/qcommonstyle.cpp.html#846
| 6 | // More specifically, this is a trimmed down version on the algorithm in: |
| 7 | // https://code.woboq.org/qt5/qtbase/src/widgets/styles/qcommonstyle.cpp.html#846 |
| 8 | QStringList viewItemTextLayout(QTextLayout& textLayout, QSize bounds, qreal& height) |
| 9 | { |
| 10 | QStringList result; |
| 11 | height = 0; |
| 12 | |
| 13 | QFontMetrics fontMetrics{ textLayout.font() }; |
| 14 | |
| 15 | textLayout.beginLayout(); |
| 16 | |
| 17 | QString str = textLayout.text(); |
| 18 | while (true) { |
| 19 | QTextLine line = textLayout.createLine(); |
| 20 | |
| 21 | if (!line.isValid()) |
| 22 | break; |
| 23 | if (line.textLength() == 0) |
| 24 | break; |
| 25 | |
| 26 | line.setLineWidth(bounds.width()); |
| 27 | height += line.height(); |
| 28 | |
| 29 | // If the *next* line has enough space to be drawn, then we don't need to elide this line. |
| 30 | if (height + fontMetrics.lineSpacing() < bounds.height()) { |
| 31 | result.append(str.mid(line.textStart(), line.textLength())); |
| 32 | } else { |
| 33 | // Otherwise, if *this* line has enough space to be drawn, draw it elided. |
| 34 | if (height < bounds.height()) { |
| 35 | result.append(fontMetrics.elidedText(str.mid(line.textStart()), Qt::ElideRight, bounds.width())); |
| 36 | } |
| 37 | // And end it here, since we know there's not enough space to draw the next line. |
| 38 | break; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | textLayout.endLayout(); |
| 43 | |
| 44 | return result; |
| 45 | } |