将 QString 转换为 char*

2021-12-09 00:00:00 string qt4 qt c++

可能的重复:
QString 到 char 的转换

我有一个函数(STL 中的 fopen),它提供一个 char* 参数作为我计算机中的路径,但我必须在那个地方使用 QString,所以它不起作用.

I have a function (fopen in STL) that gives a char* argument as a path in my computer, but I must use QString in that place so it doesn't work.

如何将QString转为char*来解决这个问题?

How can I convert QString to char* to solve this problem?

推荐答案

参见 这里是 How我可以将 QString 转换为 char*,反之亦然吗?

为了将 QString 转换为char*,那么你首先需要得到一个字符串的 latin1 表示形式调用 toLatin1() 它将返回一个 QByteArray.然后调用data()在 QByteArray 上获取指向的指针存储在字节数组中的数据.看文档:

In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:

https://doc.qt.io/qt-5/qstring.html#toLatin1https://doc.qt.io/qt-5/qbytearray.html#data

请看下面的例子演示:

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

注意,需要存储在调用 data() 之前的 bytearray它,像下面这样的调用

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.toLatin1().data();

会使应用程序崩溃,因为QByteArray 没有被存储并且因此不再存在

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

要将 char* 转换为 QString可以使用 QString 构造函数接受 QLatin1String,例如:

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:

QString string = QString(QLatin1String(c_str2)) ;

查看文档:

https://doc.qt.io/qt-5/qlatin1string.html

当然,我发现从这个以前的SO还有另一种方式答案:

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

相关文章