Qt使用Unicode转义序列创建QString

    技术2022-07-10  98

    (1)源文件保存为UTF-8,QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    #include "mainwidget.h" #include <QApplication> #include <QTextEdit> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); QString str1=QString::fromLocal8Bit("\u7a0b\u5e8f\u733f"); QString str2=QObject::tr("\u7a0b\u5e8f\u733f"); QString str3=QString::fromUtf8("\u7a0b\u5e8f\u733f"); QTextEdit textEdit; textEdit.setWindowTitle("Unicode Test"); textEdit.append(str1); textEdit.append(str2); textEdit.append(str3); textEdit.resize(400, 200); textEdit.show(); return a.exec(); }

    运行效果:

    (2)源文件保存为UTF-8,QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

    #include "mainwidget.h" #include <QApplication> #include <QTextEdit> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); QString str1=QString::fromLocal8Bit("\u7a0b\u5e8f\u733f"); QString str2=QObject::tr("\u7a0b\u5e8f\u733f"); QString str3=QString::fromUtf8("\u7a0b\u5e8f\u733f"); QTextEdit textEdit; textEdit.setWindowTitle("Unicode Test"); textEdit.append(str1); textEdit.append(str2); textEdit.append(str3); textEdit.resize(400, 200); textEdit.show(); return a.exec(); }

    运行效果:

    (3)源文件保存为GBK,QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    #include "mainwidget.h" #include <QApplication> #include <QTextEdit> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); QString str1=QString::fromLocal8Bit("\u7a0b\u5e8f\u733f"); QString str2=QObject::tr("\u7a0b\u5e8f\u733f"); QString str3=QString::fromUtf8("\u7a0b\u5e8f\u733f"); QTextEdit textEdit; textEdit.setWindowTitle("Unicode Test"); textEdit.append(str1); textEdit.append(str2); textEdit.append(str3); textEdit.resize(400, 200); textEdit.show(); return a.exec(); }

    运行效果:

    (4)源文件保存为GBK,QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

    #include "mainwidget.h" #include <QApplication> #include <QTextEdit> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); QString str1=QString::fromLocal8Bit("\u7a0b\u5e8f\u733f"); QString str2=QObject::tr("\u7a0b\u5e8f\u733f"); QString str3=QString::fromUtf8("\u7a0b\u5e8f\u733f"); QTextEdit textEdit; textEdit.setWindowTitle("Unicode Test"); textEdit.append(str1); textEdit.append(str2); textEdit.append(str3); textEdit.resize(400, 200); textEdit.show(); return a.exec(); }

    运行效果:

    结论:由上面的测试可知,unicode转义序列实际上在程序编译时被转换为了utf-8编码方式存储

     

    Processed: 0.009, SQL: 9