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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

QString has a method toStdString(). See here: doc.trolltech.com/4.5/qstring.html#toStdString. To create a QString from std::string you can use this constructor: doc.trolltech.com/4.5/qstring.html#QString-7
@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.
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());.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.