如何获取QTextEdit的字体

时间:2013-08-26 11:04:23

标签: c++ qt qtextedit

我有QTextEdit,显示包含多种字体的文字。我想用每个字符(或文本块)获取其字体信息。 我已尝试获取QTextBlock的{​​{1}}。但它似乎是一个带有ontype of font的字符串。

有没有办法获取QTextDocument的字体?

1 个答案:

答案 0 :(得分:3)

您应该可以从QTextDocument

获取此信息
QTextDocument doc;

QTextBlock currentBlock = doc.firstBlock();
while (currentBlock.isValid()) {
    QTextBlockFormat blockFormat = currentBlock.blockFormat();
    QTextCharFormat charFormat = currentBlock.charFormat();
    QFont font = charFormat.font();

    // each QTextBlock holds multiple fragments of text, so iterate over it:
    QTextBlock::iterator it;
    for (it = currentBlock.begin(); !(it.atEnd()); ++it) {
        QTextFragment currentFragment = it.fragment();
        if (currentFragment.isValid()) {
            // a text fragment also has a char format with font:
            QTextCharFormat fragmentCharFormat = currentFragment.charFormat();
            QFont fragmentFont = fragmentCharFormat.font();
            // etc...
        }
    }

    currentBlock = currentBlock.next();
}