QtextDocument对文本省略设置的方法

QtextDocument对文本省略设置的方法

Qt利用QTextDocument进行文字的省略显示

1、qT常常遇到文字的设计。有时进行文本的编辑时常常会会使文本越过边界进行显示,效果非常不好。 2、首先先利用QFontMetrics 进行文字font的省略省略设置。 3、再对文本的htmL格式设置

具体方法如下

1.1 定义一个本地保存的路径名

设计一个文本超过MaxWidth即自动省略显示的函数:

QString getElidedText(QString str, int maxWidth)
{
     QFontMetrics fontWidth(EDVersion::menuFont());
     str = fontWidth.elidedText(str, Qt::ElideRight, maxWidth - 12*UnitUtil::dpiScale96());
     return str;
}

1.2 使用以下的函数对QString文本进行格式的设置

函数如下:

QString createTextFromPlainText(const QString &plainText)
{
    QTextDocument tempDoc;
    tempDoc.setIndentWidth(edTextIdent);

    QTextCursor tcursor(&tempDoc);
    tcursor.insertText(plainText, m_textFormat.m_charFmt);
    tcursor.clearSelection();
    tcursor.movePosition(QTextCursor::Start);
    tcursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
    tcursor.setBlockFormat(m_textFormat.m_blockFmt);
    tcursor.setBlockCharFormat(m_textFormat.m_charFmt);

    m_htmlText = tempDoc.toHtml();
    m_editSize = tempDoc.size();
    if(UnitUtil::dpiScale() != 1){
        m_editSize.setWidth(m_editSize.width() / UnitUtil::dpiScale());
        m_editSize.setHeight(m_editSize.height() / UnitUtil::dpiScale());
    }
    return tempDoc.toHtml();
}

最后对设置的文本使用QTextDocument设置html写进这个文本的Cell里

具体过程:

 QTextDocument tempDoc;
 tempDoc.setHtml(tempText);

最后调用textCell的draw函数传入QPainter:便可完成文本的绘制。

##总的来说,文本的编辑分为三步: 1、获取当前文本编辑的cell; 2、对文本的输入光标、文本编辑的模式进行设置; 3、对文本的format对设置。 4、对文本进行html的格式转换。 5、调用text进行绘画。