Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using both std::string and QString interchangeably

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.

like image 750
Alan Turing Avatar asked May 26 '11 11:05

Alan Turing


1 Answers

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

like image 164
Fred Foo Avatar answered Sep 22 '22 01:09

Fred Foo