Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain const char * from QString

I have read a string in from an XML file with UTF8 encoding. I store this value in a QString object and concatenate it with some other information. I can see in the QtCreator debugger that the QString holds the desired value.

I need to pass this string to another library that takes a const char * argument. How do I obtain the const char * please? I've tried toLocal8bit(), toLatin1(), toUtf8() all with no luck. Seems like I am missing something...

like image 387
narmaps Avatar asked Sep 25 '13 03:09

narmaps


People also ask

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .

How do you convert QString to string?

You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.

Can a function return a const char?

7.8 Member Function Return Types const char* function (...) returns a pointer to data that cannot change. The caller can see the data but the compiler will reject any code that may change the data. The caller must assign the result to a const char* variable or pass as a const char* argument.

How do you initialize QString?

Generally speaking: If you want to initialize a QString from a char*, use QStringLiteral . If you want to pass it to a method, check if that method has an overload for QLatin1String - if yes you can use that one, otherwise fall back to QStringLiteral .


1 Answers

I need to pass this string to another library that takes a const char * argument. How do I obtain the const char * please? I've tried toLocal8bit(), toLatin1(), toUtf8() all with no luck. Seems like I am missing something...

Because if you try those, you only get a QByteArray back as opposed to a const char*. You could use the constData() method on the QByteArray you got that way, and then you will have the desired result.

Mixing std::string and QString is not necessary, hence it is better to go through the qt types (QString -> QByteArray -> const char*) without introducing std::string in here.

Where you use toLocal8bit(), toLatin1() or toUtf8() depends on your encoding, so that is a different question to the main one in here. They will all return a QByteArray to you.

Note: you should avoid using toAscii() though as that is deprecated in Qt 5 for good.

like image 81
lpapp Avatar answered Sep 16 '22 23:09

lpapp