解决 Qt Creator 中文字体乱码
程序员文章站
2022-03-21 11:06:19
...
使用QStringLiteral
.
ui->label_rollName->setText(QStringLiteral("中文1"));
ui->label_resultName->setText(QStringLiteral("中文2"));
官方文档:
QStringLiteral(str)
The macro generates the data for a QString out of the string literal str at compile time. Creating a QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file.
If you have code that looks like this:
// hasAttribute takes a QString argument
if (node.hasAttribute("http-contents-length")) //...
then a temporary QString will be created to be passed as the hasAttribute function parameter. This can be quite expensive, as it involves a memory allocation and the copy/conversion of the data into QString's internal encoding.
This cost can be avoided by using QStringLiteral instead:
if (node.hasAttribute(QStringLiteral(u"http-contents-length"))) //...
In this case, QString's internal data will be generated at compile time; no conversion or allocation will occur at runtime.
Using QStringLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QString instances from data known at compile time.
Note: QLatin1String can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1String and this overload avoids conversion to QString. For instance, QString::operator==() can compare to a QLatin1String directly:
if (attribute.name() == QLatin1String("http-contents-length")) //...
Note: Some compilers have bugs encoding strings containing characters outside the US-ASCII character set. Make sure you prefix your string with u in those cases. It is optional otherwise.
See also QByteArrayLiteral.
翻译:
QStringLiteral(str)宏在编译时从字符串文字str中为QString生成数据。 在这种情况下,可以从中免费创建QString,并且将生成的字符串数据存储在已编译目标文件的只读段中。
如果您的代码如下所示://如果(node.hasAttribute(“ http-contents-length”))// ... hasAttribute接受一个QString参数。
然后将创建一个临时QString作为hasAttribute函数参数传递。 这可能会非常昂贵,因为它涉及内存分配以及将数据复制/转换为QString的内部编码。
可以通过改用QStringLiteral来避免此成本:if(node.hasAttribute(QStringLiteral(u“ http-contents-length”)))// ...
在这种情况下,QString的内部数据将在编译时生成。 在运行时不会发生任何转换或分配。
使用QStringLiteral而不是用双引号引起来的纯C ++字符串文字可以显着加快根据编译时已知的数据创建QString实例的速度。
注意:当将字符串传递给具有重载QLatin1String的函数时,QLatin1String仍比QStringLiteral更有效,并且此重载可避免转换为QString。 例如,QString :: operator ==()可以直接与QLatin1String进行比较:if(attribute.name()== QLatin1String(“ http-contents-length”))// ...
注意:某些编译器的bug编码字符串包含US-ASCII字符集以外的字符。 在这种情况下,请确保在字符串前加上u。 否则是可选的。
另请参见QByteArrayLiteral。
上一篇: react native 添加自定义字体