我有一个输入QString,它有HTML 4实体,就像我想解码的õ
一样。但是我在Qt中找不到任何设施来做到这一点。有没有办法在Qt中做到这一点?如果可能的话,我想避免QTextDocument
这样我就不必引入QtGui。
HTML 4 实体列在此链接中:
https://www.w3schools.com/charsets/ref_html_entities_4.asp
出于好奇,我环顾四周。
我发现这个是:如何在 QT 中将实体字符(转义字符(转换为 HTML?但是,它使用OP想要防止的QTextDocument
(这是GUI的一部分(。
QTextDocument::setHtml()
的文档没有提到任何具体的东西是否被使用可以直接访问(甚至是Qt核心的一部分(。因此,我研究了源代码。我从 woboq.orgQTextDocument::setHtml()
开始,然后跟着面包屑。
最后,我最终得到了qtbase/src/gui/text/qtexthtmlparser.cpp
:
QString QTextHtmlParser::parseEntity()
{
const int recover = pos;
int entityLen = 0;
QStringRef entity;
while (pos < len) {
QChar c = txt.at(pos++);
if (c.isSpace() || pos - recover > 9) {
goto error;
}
if (c == QLatin1Char(';'))
break;
++entityLen;
}
if (entityLen) {
entity = QStringRef(&txt, recover, entityLen);
QChar resolved = resolveEntity(entity);
if (!resolved.isNull())
return QString(resolved);
if (entityLen > 1 && entity.at(0) == QLatin1Char('#')) {
entity = entity.mid(1); // removing leading #
int base = 10;
bool ok = false;
if (entity.at(0).toLower() == QLatin1Char('x')) { // hex entity?
entity = entity.mid(1);
base = 16;
}
uint uc = entity.toUInt(&ok, base);
if (ok) {
if (uc >= 0x80 && uc < 0x80 + (sizeof(windowsLatin1ExtendedCharacters)/sizeof(windowsLatin1ExtendedCharacters[0])))
uc = windowsLatin1ExtendedCharacters[uc - 0x80];
QString str;
if (QChar::requiresSurrogates(uc)) {
str += QChar(QChar::highSurrogate(uc));
str += QChar(QChar::lowSurrogate(uc));
} else {
str = QChar(uc);
}
return str;
}
}
}
error:
pos = recover;
return QLatin1String("&");
}
可以在同一源文件中找到命名实体的表:
static const struct QTextHtmlEntity { const char name[9]; quint16 code; } entities[]= {
{ "AElig", 0x00c6 },
{ "AMP", 38 },
。
{ "zwj", 0x200d },
{ "zwnj", 0x200c }
};
Q_STATIC_ASSERT(MAX_ENTITY == sizeof entities / sizeof *entities);
这些对OP来说是个坏消息:
QTextHtmlParser
的 API 是私有的:// // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. //
它是Qt GUI的一部分。
如果OP坚持防止GUI依赖,我看到的唯一其他机会是复制代码(或者只是从头开始重新实现它(。