Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++17

qt

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?

like image 969
Vadim Peretokin Avatar asked Sep 03 '25 17:09

Vadim Peretokin


1 Answers

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())
like image 151
Remy Lebeau Avatar answered Sep 05 '25 15:09

Remy Lebeau