qt 获取纯文本自动换行的每一行内容

使用QTextOption设置是否换行等文本属性,QTextLayout计算文本显示内容

#include <QtGui/QTextLayout>
#include <QtCore/QtMath>

QStringList GetMultiLineText(const QFont& fnt, const QString& text, int width)
{
    QTextLayout textLayout(text, fnt);
    textLayout.setCacheEnabled(true);
    QTextOption option = textLayout.textOption();
    option.setWrapMode(QTextOption::WrapMode::WrapAtWordBoundaryOrAnywhere);
    textLayout.setTextOption(option);
    //计算显示行数以及每一行文本内容
    {
        qreal height = 0;
        //qreal width = 0;
        qreal lineWidth = 0x01000000;
        lineWidth = qMax<qreal>(0, width);
        textLayout.beginLayout();
        QFontMetricsF fm(fnt);
        qreal leading = fm.leading();
        height = -leading;

        while (1) {
            QTextLine line = textLayout.createLine();
            if (!line.isValid())
                break;

            line.setLineWidth(lineWidth);
            height += leading;

            // Make sure lines are positioned on whole pixels
            height = qCeil(height);
            line.setPosition(QPointF(0., height));
            height += line.height();
            //width = qMax(width, l.naturalTextWidth());
        }
        textLayout.endLayout();
    }

    QStringList list;
    for (int i = 0; i < textLayout.lineCount(); ++i)
    {
        QTextLine line = textLayout.lineAt(i);
        int start = line.textStart(); //开始字符位置
        int length = line.textLength(); // 字符长度

        QString lineText = text.mid(start, length);
        list.push_back(lineText);
    }

    return list;
}
posted @ 2021-10-22 16:28  川野散人  阅读(1041)  评论(0)    收藏  举报