I use Qt extensively in a software system I'm working on for graphical and GUI components. However, for most internal algorithms and processing of data Qt plays a smaller role.
I'll often run into the need to convert from std::string to QString or visa versa. My inclination is to use std::string as much as possible and use QString only when I need to pass strings to Qt classes like those that work with the file system.
As I was programming this morning, it hit me that it may be bad design to have both std::string and QString sprinkled throughout my code. Should I completely switch to QString? Has anyone else run into this design choice?
Qt provides a lot of the same functionality of STL, but I'm still hesitant switching completely since Qt is less standardized and stable.
Yes, I've had this situation before. The program I worked on used Qt throughout, but I had to hook it up to a library that expected std::string
. The benefit of QString
is that it explicitly uses Unicode, while the C++ standard library makes no guarantees about encoding.
The solution was to convert at the boundary of this library with
QString toQString(std::string const &s)
{
return QString::fromUtf8(s.c_str());
}
std::string fromQString(QString const &s)
{
return std::string(s.toUtf8().data());
}
since the library produced std::string
's containing UTF-8.
What you seem to want is the exact opposite: use std::string
throughout and convert at the Qt boundary. That seems perfectly ok; it takes a bit more work than always using QString
, but you'll have to put in effort when you need a non-QString
-accepting library anyway, and your non-GUI components don't depend on Qt (hurrah!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With