How to convert QString to char*
时间: 2024-02-21 11:58:02 浏览: 168
To convert a `QString` to a `char*`, you can use the `toUtf8()` method to convert the string to a `QByteArray`, and then use the `data()` method to get a pointer to the underlying `char*` data:
```c++
QString str = "Hello, world!";
QByteArray ba = str.toUtf8();
const char* c_str = ba.data();
```
Note that the `data()` method returns a `const char*`, which means you cannot modify the string through this pointer. If you need to modify the string, you can create a copy of the `QByteArray`:
```c++
QString str = "Hello, world!";
QByteArray ba = str.toUtf8();
char* c_str = ba.data(); // This is a const pointer, cannot modify the string
QByteArray writable_ba = ba; // Create a copy
char* writable_c_str = writable_ba.data(); // This pointer can be used to modify the string
```
阅读全文