Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] Convert std::string to QString in Qt 4.8.1?



  • Hi
    I have a std::string myString which needs to be converted to QString?
    How do I do this?
    I am aware of following method:

    @QString myQString = QString::fromAscii(myString.c_str(), myString.length());@

    But the problem is that I have millions of such strings.
    So I would like to know the most efficient method for this translation?



  • Wont QString::fromStdString() work ?



  • The documentation says

    bq. This constructor is only available if Qt is configured with STL compatibility enabled.

    What does this mean?



  • When compiling Qt from source you can disable support for these functions but to my knowledge the pre-compiled distribution is compiled with the support enabled.

    However: fromStdString always assumes ascii encoding, so using it is a bad idea unless the strings are internal strings or you're sure your code will never come into contact with non-english languages.

    Otherwise your strings might contain utf8 or a local 8 bit encoding (i.e. latin1) so fromAscii or fromStdString will lose information.

    You should work with QString::fromLocal8Bit or QString::fromUtf8, depending on where the c-strings come from.



  • [quote author="Tannin" date="1388850668"]When compiling Qt from source you can disable support for these functions but to my knowledge the pre-compiled distribution is compiled with the support enabled.

    However: fromStdString always assumes ascii encoding, so using it is a bad idea unless the strings are internal strings or you're sure your code will never come into contact with non-english languages.

    Otherwise your strings might contain utf8 or a local 8 bit encoding (i.e. latin1) so fromAscii or fromStdString will lose information.

    You should work with QString::fromLocal8Bit or QString::fromUtf8, depending on where the c-strings come from.[/quote]

    I believe this has changed in Qt 5.

    https://qt-project.org/doc/qt-5.0/qtcore/qstring.html#fromStdString



  • @tanin thanks for the information.
    I am working with numbers, so it will always be ASCII.
    @t3685 great improvement I think.


Log in to reply