Search code examples
qtc++17

How to best convert a std::string_view to QString?


I have a library that gives me a string_view. What's the best way to get it into a QString (not a QStringView)?

I made QString::fromStdString(std::string(key).c_str()), but is that the best?


Solution

  • Drop the c_str(), you don't need it, since fromStdString() takes a std::string (hence the name):

    QString::fromStdString(std::string(key))
    

    That being said, if the std::string_view is null-terminated (which is not guaranteed), you can use the QString constructor that accepts a char*:

    QString(key.data())
    

    Or, if the std::string_view is encoded in Latin-1, you can use:

    QString::fromLatin1(key.data(), key.size())
    

    Or, if encoded in UTF-8:

    QString::fromUtf8(key.data(), key.size())
    

    Or, if encoded in the user's default locale:

    QString::fromLocal8Bit(key.data(), key.size())