简体   繁体   English

QTextEdit不显示键盘上不可用的特殊字符

[英]QTextEdit doesn't display special characters not available on keyboard

I have to display some special characters like ¼, ½ etc. in a QTextEdit which are not on the QWERTY keyboard.I am able to type these characters in the QTextEdit and also able to paste them. 我必须在QTextEdit中显示一些不在QWERTY键盘上的特殊字符,例如¼,½等。我可以在QTextEdit中键入这些字符,也可以粘贴它们。 But when I try to programatically set these characters QTextEdit displays an extra character 'Â'. 但是,当我尝试以编程方式设置这些字符时,QTextEdit显示一个额外的字符“”。

I do not get this problem while typing and pasting. 键入和粘贴时没有出现此问题。 These characters are typed with some Alt+[code] codes. 这些字符用一些Alt + [code]码键入。

I am using Qt 4.8 on Windows 8 64bit. 我在Windows 8 64bit上使用Qt 4.8。

#include<QtGui>

int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
QTextEdit t;
    t.setPlainText("¼2½  \n");              // QTextEdit displays=> ¼2½
    //    t.setHtml("¼2½  \n");             // QTextEdit displays=> ¼2½
    //    t.insertHtml("¼2½  \n");          // QTextEdit displays=> ¼2½
    //    t.insertPlainText("¼2½  \n");     // QTextEdit displays=> ¼2½
// also tried setHtml() with HTML code which works in Firefox didn't help me 
    t.show();
    return a.exec();
}

How can I put these characters in a QTextEdit programatically without this extra character? 如何在没有此多余字符的情况下以编程方式将这些字符放入QTextEdit?

Your source code needs to be written in UTF-8 encoding, and you should use QStringLiteral in Qt 5 or QString::fromUtf8 in Qt 4. You won't have that problem then. 您的源代码需要以UTF-8编码编写,并且应该在Qt 5中使用QStringLiteral或在Qt 4中使用QString::fromUtf8 ,这样就不会有问题。

Eg: 例如:

t.setPlainText(QStringLiteral("¼, ½"));    // Qt 5
t.setPlainText(QString::fromUtf8("¼, ½")); // Qt 4

Ensure that the editor you're using is set to encode the file as UTF-8, not Latin 1 etc. 确保将您使用的编辑器设置为将文件编码为UTF-8,而不是Latin 1等。

Use QTextCodec to display characters in UTF-8 encoding. 使用QTextCodec以UTF-8编码显示字符。

#include <QTextCodec>
...
QTextCodec* codec=QTextCodec::codecForName("UTF-8");
//    QTextCodec::setCodecForLocale(codec); //if you want everything to be in UTF-8
QTextCodec::setCodecForCStrings(codec);
QApplication a(argc, argv);
...

Or convert characters in place: 或就地转换字符:

t.setPlainText(QObject::trUtf8("¼2½  \n"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM