I'm writing an Syntax Highlighter with Qt6 CMake. When I using QFile and QXmlStreamReader to read and parsing my Keyword Lists (a XML File) will show these errors:
Failed to open XML file
Path: ":/config/Configuration/RCodeEditor/KeywordList/cppKeywords.xml"
QIODevice::read (QFile, ":\config\Configuration\RCodeEditor\KeywordList\cppKeywords.xml"): device not open
XML parsing error: "Premature end of document."
And the related function is:
QStringList readKeywords(const QString &filePath) {
QStringList names;
QFile file(filePath);
// if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
// qDebug() << "Value of File Path" << filePath;
// qDebug() << "Failed to open XML file:" << file.errorString();
// return names;
// }
qDebug() << "Path:" << filePath;
QXmlStreamReader xmlReader(&file);
while (!xmlReader.atEnd() && !xmlReader.hasError()) {
QXmlStreamReader::TokenType token = xmlReader.readNext();
if (token == QXmlStreamReader::StartElement && xmlReader.name().toString() == "name") {
QString name = xmlReader.readElementText();
names.append(name);
}
}
if (xmlReader.hasError()) {
qWarning() << "XML parsing error:" << xmlReader.errorString();
}
// file.close();
return names;
I'm trying to comment some 'meaningless' code blocks such as file.close() and others.
But it still meaningless for me.
The .qrc file is showned here:
<RCC>
<qresource prefix="/config">
<file>Configuration/RCodeEditor/KeywordList/cppKeywords.xml</file>
<file>Configuration/RCodeEditor/KeywordList/doxygenTags.xml</file>
</qresource>
<RCC>
And the keyword list file is here, too:
<?xml version="1.0" encoding="UTF-8" ?>
<RetoCodeEditor>
<KeywordList>
<KContent>
<keyword name = "alignas">
<name>alignas</name>
</keyword>
<keyword name="alignof">
<name>alignof</name>
</keyword>
<keyword name="and">
<name>and</name>
</keyword>
<keyword name="and_eq">
<name>and_eq</name>
</keyword>
<keyword name="asm">
<name>asm</name>
</keyword>
<keyword name="auto">
<name>auto</name>
</keyword>
<!-- And so many others -->
</KContent>
</KeywordList>
</RetoCodeEditor>
This is a very serious question that I have need to solved for my code editor. Thank you very much!
Usage on the Constructor of Syntax Highlighter
explicit RCFamilyHighlighter(QTextDocument *parent = nullptr) : QSyntaxHighlighter(parent) {
initRegexp(); //Initialize Regular Expressions
readAndSetStyle(":/config/Configuration/RCodeEditor/ColorThemes/Dracula.xml"); //Read and set default color theme
QStringList keywordsL;
keywordsL = readKeywords(":/config/Configuration/RCodeEditor/KeywordList/cppKeywords.xml");
// QStringList doxygenTagsList;
// doxygenTagsList = readKeywords(":/config/Configuration/RCodeEditor/KeywordList/doxygenTags.xml");
for (const QString &pattern: keywordsL) {
highlightingRules.append({QRegularExpression("\\b" + pattern + "\\b"), keywordFormat});
}