我想在QT中将实体字符(转义字符)转换为HTML,请帮助我....
即:我想将"
替换为"
,将>
替换为>
=====这是我的代码无效====
QString MyApp::ReplaceString(const QString Data, const QString &Before, const QString &After)
{
QString Result = Data;
Result.replace(Before, After, Qt::CaseInsensitive);
return Result;
}
======
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QByteArray data=pReply->readAll();
QString str = codec->toUnicode((const char *)data);
str = Qt::escape(str);
str = ReplaceString(str, """, "\"");
str = ReplaceString(str,">", ">");
答案 0 :(得分:14)
我不确定我理解你想要什么,只是猜测。您可以使用QTextDocument。尝试这样的事情:
QTextDocument text;
text.setHtml("<>"");
QString plain = text.toPlainText();
qDebug("%s.", qPrintable(plain));
请记住,QTextDocument需要gui模块。
答案 1 :(得分:2)
我认为这可以解决您的问题。
QString escaped=
QString(myhtml).replace("&","&").replace(">",">").replace("<","<");
答案 2 :(得分:1)
测试escape()
功能:
QString plain = "#include <QtCore>"
QString html = Qt::escape(plain);
// html == "#include <QtCore>"
和convertFromPlainText()
功能:
QString Qt::convertFromPlainText ( const QString & plain, WhiteSpaceMode mode = WhiteSpacePre )
答案 3 :(得分:1)
您好,将非ASCII字符转换为&amp;# XXX ; (其中 XXX 是一个数字):
/***************************************************************************//*!
* @brief Encode all non ASCII characters into &#...;
* @param[in] src Text to analyze
* @param[in,opt] force Force the characters "list" to be converted.
* @return ASCII text compatible.
*
* @note Original code: http://www.qtforum.org/article/3891/text-encoding.html
*
* @warning Do not forget to use QString::fromUtf8()
*/
QString encodeEntities( const QString& src, const QString& force=QString() )
{
QString tmp(src);
uint len = tmp.length();
uint i = 0;
while( i<len )
{
if( tmp[i].unicode() > 128 || force.contains(tmp[i]) ){
QString rp = "&#"+QString::number(tmp[i].unicode())+";";
tmp.replace(i,1,rp);
len += rp.length()-1;
i += rp.length();
}else{
++i;
}
}
return tmp;
}
/***************************************************************************//*!
* @brief Allows decode &#...; into UNICODE (utf8) character.
* @param[in] src Text to analyze
* @return UNICODE (utf8) text.
*
* @note Do not forget to include QRegExp
*/
QString decodeEntities( const QString& src )
{
QString ret(src);
QRegExp re("&#([0-9]+);");
re.setMinimal(true);
int pos = 0;
while( (pos = re.indexIn(src, pos)) != -1 )
{
ret = ret.replace(re.cap(0), QChar(re.cap(1).toInt(0,10)));
pos += re.matchedLength();
}
return ret;
}
基本用法:
qDebug() << encodeEntities(QString::fromUtf8("éà@<>hello the world €"),QString("<>"));
// Will print: éà@<>hello the world €
qDebug() << decodeEntities("aßéplopéàçê€");
// Will print: hello world