我正在使用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关键字为粗体时,它仅输出一个块“用于测试的类”和一种格式“用于测试的类”。
谢谢你的帮助 !
最佳答案
好的,我是从QSyntaxHighlighter::setFormat的文档中找到的:
语法荧光笔应用的格式未存储在QTextBlock::charFormat中,而是存储在其他格式中:
QVector<QTextLayout::FormatRange> formats = textEdit->textCursor().block().layout()->formats();