Search code examples
c++qtqt4

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. But when I try to programatically set these characters QTextEdit displays an extra character 'Â'.

I do not get this problem while typing and pasting. These characters are typed with some Alt+[code] codes.

I am using Qt 4.8 on Windows 8 64bit.

#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?


Solution

  • Use QTextCodec to display characters in UTF-8 encoding.

    #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"));