How can I convert a QString to char* and vice versa?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/carlhelen/article/details/82525932

 

In order to convert a QString http://doc.qt.io/qt-5/qstring.html to a char*, then you first need to get a local8Bit representation of the string by calling toLocal8Bit() http://doc.qt.io/qt-5/qstring.html#toLocal8Bit on it which will return a QByteArray http://doc.qt.io/qt-5/qbytearray.html. Then call data() http://doc.qt.io/qt-5/qbytearray.html#data on the QByteArray to get a pointer to the data stored in the byte array.

See the following example for a demonstration:

    int main(int argc, char **argv)
    {
     QApplication app(argc, argv);
      QString str1 = "Test";
      QByteArray ba = str1.toLocal8Bit();
      const char *c_str2 = ba.data();
      printf("str2: %s", c_str2);
      return app.exec();
    }

Note that it is necessary to store the bytearray before you call data() on it, a call like the following

const char *c_str2 = str2.toLocal8Bit().data();

will make the application crash as the QByteArray has not been stored and hence no longer exists

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String http://doc.qt.io/qt-5/qlatin1string.html to ensure the locale encoded string is correct with fromLocal8Bit() http://doc.qt.io/qt-5/qstring.html#fromLocal8Bit, e.g:

QString string = QString(QLatin1String(c_str2));
QString string = QString::fromLocal8Bit(c_str2);

In addition, if you want to just print out the string then you can use qPrintable() http://doc.qt.io/qt-5/qtglobal.html#qPrintable as a quick means to do this without having to convert to a char *. For example:

printf("str2: %s", qPrintable(str1));

猜你喜欢

转载自blog.csdn.net/carlhelen/article/details/82525932