9

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Alan Turing
  • 12,223
  • 16
  • 74
  • 116

2 Answers2

9

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 2
    `QString` has a method `toStdString()`. See here: http://doc.trolltech.com/4.5/qstring.html#toStdString. To create a `QString` from `std::string` you can use this constructor: http://doc.trolltech.com/4.5/qstring.html#QString-7 – yasouser Jun 01 '11 at 18:37
  • 1
    @yasourer: yes, but those depend on a globally set character encoding. These functions come from a library which got `std::string`'s from another library, always containing UTF-8. – Fred Foo Jun 01 '11 at 20:18
  • 1
    You can improve those functions to work even if the strings contain embedded NULs, by passing the length as well - `return QString::fromUtf8(s.c_str(), s.size())` and `auto buf = s.toUtf8(); return std::string(buf.data(), buf.size());`. – Toby Speight Aug 24 '17 at 08:28
6

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.

tibur
  • 11,531
  • 2
  • 37
  • 39