Qstring and Chinese, qstring and std::wstring conversion (using fromstdwstring and U8 keywords)

Source: Internet
Author: User

QT Version: 5.5.1

Qt's qstring is rich in functionality, and support for non-English languages is not a problem, but not directly supported. For example, like

?
1 QString str("死亡使者赛维");

This is directly constructed with a Chinese string, so the Qmessagebox display str will appear garbled. If you use functions such as Fromlocal8bit, fromLatin1, and dependent on the display language of the local computer, they are not a good method.

It is a good practice to explicitly use wide characters (wchar_t) or UTF-8.

?
12 QString str0(QString::fromStdWString(L"数学分析"));QString str1(QString::fromUtf8(u8"高等代数")); // C++11

UTF-8 string literal is the content of c++11, if your compiler does not support it, you can use the first way. In this way, whatever the local language is, it can be all-in-one.

Test it!

?
1234567891011121314 voidMsgBox(constQString &s){    QMessageBox::information(nullptr, QString::fromUtf8(u8"标题"), s, QMessageBox::Ok);}voidMainWindow::on_pushButton_clicked(){    QString str0(QString::fromStdWString(L"数学分析"));    QString str1(QString::fromUtf8(u8"高等代数"));    QString str2(QString::fromUtf8(u8"ステンカラーのコート 【折式立领的外套】")); // 日文也不是问题    QString s(QString::fromUtf8(u8"\r\n"));    MsgBox(str0 + s + str1 + s + str2);}

Operation Result:

Finally, we give the mutual conversion between qstring and std::wstring.

From std::wstring to qstring, use the static member function of Qstring qstring::fromstdwstring. It takes a parameter of type std::wstring and returns the corresponding qstring.

?
12 std::wstring str_STL(L"实变函数论");QString str_Qt = QString::fromStdWString(str_STL);

From qstring to std::wstring, use the qstring member function qstring::tostdwstring. It returns a std::wstring.

?
1 std::wstring str_STL = str.toStdWString();

http://my.oschina.net/jthmath/blog/521458

Qstring and Chinese, qstring and std::wstring conversion (using fromstdwstring and U8 keywords)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.