QSyntaxHighlighter不创建QTextFragments

时间:2019-04-23 06:42:31

标签: c++ qt syntax-highlighting syntaxhighlighter

我正在使用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();
}

并且当class关键字为粗体时,它仅输出一个块“用于测试的类”和一种格式“用于测试的类”。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

好吧,我是从QSyntaxHighlighter::setFormat的文档中找到的:

  

请注意,文档本身未更改通过此功能设置的格式。

语法荧光笔所应用的格式未存储在QTextBlock :: charFormat中,而是存储在其他格式中:

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