QString编码转换

26 篇文章 1 订阅

QString是QT中对于字符串的存储和处理的类,类似于MFC中的CString,如果用过的话就知道比std中的string和wstring要好用的多,功能也更强大。QString内部是将字符串保存为Unicode编码的,所以无论传入的字符串是什么编码,都会将其转为Unicode,那有一个问题就需要明确:

QString构建的时候是如何知道传入的是什么编码的?

这个就要看QString的构造函数了:

QString::QString(const char *str)
Constructs a string initialized with the 8-bit string str. The given const char pointer is converted to Unicode using the fromUtf8() function.

You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful if you want to ensure that all user-visible strings go through QObject::tr(), for example.

Note: Defining QT_RESTRICTED_CAST_FROM_ASCII also disables this constructor, but enables a QString(const char (&ch)[N]) constructor instead. Using non-literal input, or input with embedded NUL characters, or non-7-bit characters is undefined in this case.

上面是QT文档中的说明,如果传入的是char*字符串,默认这个字符串是以utf-8编码的,就类似于调用了QString::fromUtf8。

所以如果是将char*字符串给QString,要确保字符串是utf-8编码的,否则QString在转码到Unicode时会出错。

QString::fromStdString也是将std::string中的字符串当做utf-8编码来处理的。

应该像下面这样使用: 

QString s = u8"中国";
QString s = QString::fromUtf8(u8"中国");
std::string stdS = u8"中国";
QString s = QString::fromStdString(stdS);

另外还有关于编码的QString::fromLocal8bit是会受到本地设置的影响的,QTextCodec::setCodecForLocale,不建议使用这种方式。所以在编写代码过程中最好就是将所有源字符串以utf-8编码,这样在使用时就不必考虑到太多转换的细节。

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值