2

For plaintext there is QFontMetrics::elideText (https://doc.qt.io/qt-5/qfontmetrics.html#elidedText). This doesn't work with rich text though.

How can we elide rich text in Qt?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Raven
  • 2,951
  • 2
  • 26
  • 42
  • 1
    There is an [old QT bug report](https://bugreports.qt.io/browse/QTBUG-1837) for asking this feature. You can vote for it. – Pamputt Jun 30 '23 at 09:05

1 Answers1

2

This function can elide rich text. It uses a QTextDocumet for representing the rich text and a QTextCursor to manipulate the rich text.

It's probably not the most efficient way to do this but it seems to work.

QString elideRichText(const QString &richText, int maxWidth, QFont font) {
    QTextDocument doc;
    doc.setTextMargin(0);
    doc.setHtml(richText);
    doc.adjustSize();

    if (doc.size().width() > maxWidth) {
        // Elide text
        QTextCursor cursor(&doc);
        cursor.movePosition(QTextCursor::End);

        const QString elidedPostfix = "...";
        QFontMetrics metric(font);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
        int postfixWidth = metric.horizontalAdvance(elidedPostfix);
#else
        int postfixWidth = metric.width(elidedPostfix);
#endif
        while (doc.size().width() > maxWidth - postfixWidth) {
            cursor.deletePreviousChar();
            doc.adjustSize();
        }

        cursor.insertText(elidedPostfix);

        return doc.toHtml();
    }

    return richText;
}
Raven
  • 2,951
  • 2
  • 26
  • 42