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?
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?
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;
}