QSyntaxHighlight不会创建QTextFragments

QSyntaxHighlighter does not create QTextFragments

本文关键字:QTextFragments 创建 QSyntaxHighlight      更新时间:2023-10-16

我正在使用Qt开发语法突出显示器,我想在其上添加单元测试以检查格式是否应用良好。但是我无法按格式划分块。我使用 QTextBlock 和 QTextFragment,但它不起作用,而 QTextFragment 的文档说:

文本

片段描述以单个字符格式存储的一段文本。

这是可运行的 main.cpp 文件中的代码:

#include <QApplication>
#include <QTextEdit>
#include <QSyntaxHighlighter>
#include <QRegularExpression>
#include <QDebug>
class Highlighter : public QSyntaxHighlighter
{
public:
    Highlighter(QTextDocument *parent)
        : QSyntaxHighlighter(parent)
    {}
protected:
    void highlightBlock(const QString& text) override
    {
        QTextCharFormat classFormat;
        classFormat.setFontWeight(QFont::Bold);
        QRegularExpression pattern { "\bclass\b" };
        QRegularExpressionMatchIterator matchIterator = pattern.globalMatch(text);
        while (matchIterator.hasNext())
        {
            QRegularExpressionMatch match = matchIterator.next();
            setFormat(match.capturedStart(), match.capturedLength(), classFormat);
        }

        // ==== TESTS ==== //
        qDebug() << "--------------------------------";
        QTextDocument *doc = document();
        QTextBlock currentBlock = doc->firstBlock();
        while (currentBlock.isValid()) {
            qDebug() << "BLOCK" << currentBlock.text();
            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();
                    qDebug() << "FRAGMENT" << currentFragment.text();
                }
            }
            currentBlock = currentBlock.next();
        }
    }
};
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    auto *textEdit = new QTextEdit;
    auto *highlighter = new Highlighter(textEdit->document());
    Q_UNUSED(highlighter);
    textEdit->setText("a class for test");
    textEdit->show();
    return a.exec();
}

它只输出一个块"一个测试类"和一个格式"一个测试类",而类关键字是粗体。

感谢您的帮助!

好的,

我从QSyntaxHighlighter的文档中找到了这个::setFormat:

请注意,通过此函数设置的格式不会修改文档本身。

语法突出显示器应用的格式不存储在 QTextBlock::charFormat 中,而是存储在其他格式中:

QVector<QTextLayout::FormatRange> formats = textEdit->textCursor().block().layout()->formats();