Qt:省略富文本 [英] Qt: Elide rich text

查看:61
本文介绍了Qt:省略富文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于纯文本,有 QFontMetrics::elideText (https://doc.qt.io/qt-5/qfontmetrics.html#elidedText).但这不适用于富文本.

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

我们如何在 Qt 中删除富文本?

How can we elide rich text in Qt?

推荐答案

此功能可以省略富文本.它使用 QTextDocumet 表示富文本,使用 QTextCursor 操作富文本.

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

这篇关于Qt:省略富文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆