我不能在Qt类之外的Qt 5.5中使用tr()

I can't use tr() in Qt 5.5 outside the Qt classes

本文关键字:Qt tr 不能      更新时间:2023-10-16

我是一个小初学者,我在Qt中实现tr函数有问题,如果我在Qt类之外使用tr("string"),我会得到错误。我发现了信息,我应该在tr()之前使用QObject::,但是如果我尝试使用

temp += QObject::tr("Example"); // temp is std::string

我得到错误

C2679: binary '+=' : no operator found which takes a right-hand operand of type 'QString' (or there is no acceptable conversion)

另一个例子:

    QString filename="example.txt";
    QFile log(QDir::currentPath() + "//" + filename);
    if ( log.open(QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text) )
    {
    QTextStream plik( &log );
    plik.setCodec("UTF-8");
    (...)
    plik << QString::fromUtf8(QObject::tr("Example2")); // Error
    }

我得到错误

C2665: 'QString::fromUtf8' : none of the 2 overloads could convert all the argument types
有人能帮我解决这个问题吗?

Qt有这么多的访问器和QString::toStdString()。

temp += QObject::tr("Example").toStdString(); // temp is std::string

表示需要转换为Utf8字节数组的流:

plik << QObject::tr("Example2").toUtf8(); // fixed

或者更好的是它也接受QString

plik << QObject::tr("Example2"); // will do