gpt4 book ai didi

c++ - QSyntaxHighlighter 不创建 QTextFragments

转载 作者:行者123 更新时间:2023-11-30 04:48:24 27 4
gpt4 key购买 nike

我正在使用 Qt 开发语法荧光笔,我想在其上添加单元测试以检查格式是否得到了很好的应用。但我没能按格式划分块。我使用 QTextBlock 和 QTextFragment 但它在 QTextFragment 的文档时不起作用说:

A text fragment describes a piece of text that is stored with a single character format.

这是可运行的 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();
}

并且它只输出一个 block “a class for test”和一种格式“a class for test”,而 class 关键字以粗体显示。

感谢您的帮助!

最佳答案

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

Note that the document itself remains unmodified by the format set through this function.

语法高亮器应用的格式不存储在 QTextBlock::charFormat 中,而是存储在附加格式中:

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

关于c++ - QSyntaxHighlighter 不创建 QTextFragments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55805666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com