为什么 Utf-8 在 Qt 5 中不能工作?

How Utf-8 may not work in Qt 5?

我有一个原始测试:msvc2015和Qt5.9.3中的项目。 文件 main.cpp 以 Unicode 格式保存为 UTF-8,签名为:

我尝试显示应该显示一些俄语文本的消息框。全部代码:

#include <QtWidgets/QApplication>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString ttl = QString::fromUtf8("russian_word_1");
    QString txt = QString::fromUtf8("russian_word_2");

    QMessageBox::information(nullptr, ttl, txt);

    return a.exec();
}

我收到的是:

这怎么可能?


更新 1: 我想将 UTF-8 与 BOM 一起使用 according to the Whosebug author's statement:

...It does not make sense to have a string without knowing what encoding it uses ���


更新 2: 在这种特殊情况下,很可能是编译器中的错误。

不要在代码中使用非英语 ASCII。因为编译依赖于编译器,源文件编码等。只写英文文本,包裹在tr(""). Create translation files, load them. Read about internalization in qt.

Another usefull link.

使用 QByteArray 作为您的消息文本,然后将其获取为 unicode QString 以供显示:

 int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec *codec1 = QTextCodec::codecForName("CP1256");
    // Converted Text:
    QByteArray myLanguage = "لا لا لا لا لا لا لا ";
    QString myLanguage2unicode = codec1->toUnicode(myLanguage);
    // Non converted text:
    QString txt = QString::fromUtf8("لا لا لا لا لا لا لا  ");

      QMessageBox::information(nullptr, myLanguage2unicode, txt);

    return a.exec();
}

以上代码的结果:

如果编译器为具有 BOM 的 UTF-8 源文件生成垃圾字符串,则这是编译器中的错误。但是,首先使用带有 UTF-8 is not recommended 的 BOM。除非你确实有理由,否则你不应该使用它。

此外,您不需要进行显式 fromUtf8() 转换。你可以这样做:

QString ttl = "russian_word_1";
QString txt = "russian_word_2";

QString 假定字符串文字是 UTF-8。来自 documentation:

In all of the QString functions that take const char * parameters, the const char * is interpreted as a classic C-style '[=17=]'-terminated string encoded in UTF-8.

您可以使用 QStringLiteral 来包装字符串文字作为优化,但这不是必需的。

最后,如果您想将应用程序从俄语翻译成其他语言,您可以使用 tr() 来包装字符串文字。通常使用 tr() 是个好主意,以防您以后决定进行翻译。

请注意,源代码中包含非英语字符串通常没有问题。这就是 UTF-8(和一般的 Unicode)的用途。所有现代编译器都支持它。然而,大多数人不赞成的是非英语 code:

auto индекс = 0; // Please don't.

但非英语 字符串 没问题。

如果您使用 Qt Creator + MSVC 编译器,这可能对您有所帮助。

TLDR:

  1. 将所有源文件保存为 UTF-8 没有 BOM
  2. 在您的 .pro 文件中添加此行: QMAKE_CXXFLAGS += /utf-8

完成!

参考资料:

  1. 将源和可执行字符集设置为 UTF-8 的 MSVC 编译器标志
  2. Add compiler flag in Qt Creator