Using both std::string and QString interchangeably

2019-04-22 17:47发布

问题:

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.

回答1:

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!).



回答2:

I would say use std::string in your program core, and convert them to QString when your are working on GUI part. I you ever want to change your GUI toolkit, that will be easier.