Qstring to const char*
I'm trying to use QList to send data via serial port.
command << "ant.hold.az -60\n"
How should I convert qstring to send data with QIODevice::write(const char * data)?
Thanks fot help.
char *cdata = sdata.toLocal8Bit().data();@
First you need to join the strings together into a single string object.
Method 1: Straightforward concatenation
foreach (QString s, command)
result += s;
Method 2: Use QStringList
QString result = commandSL.join("");
The choice between the above two depends on how long your list, and the strings in it, are. If you are doing relatively light operation, straightforward concatenation is better, because QString probably has enough pre-allocated space for simple copying. If the strings you are dealing with is quite long, however, you should use QStringList and join.
Now, with a single QString instance, you can convert it to const char * quite easily. Simply select one of the methods that convert a QString into QByteArray based on the encoding you wish to use (toUtf8, toLatin1, etc.), and then call constData on the QByteArray, e.g.
const char *data = result.toUtf8().constData();
Check the docs for more information.
Again, thanks for help!
You can use the write(const QByteArray &byteArray) overload, that will save you some line of codes.
And possibly some memory access error
@char *cdata = sdata.toLocal8Bit().data();@
toLocal8Bit() returns a temporary QByteArray that will exist only during this line.
@QByteArray local8Bit = sdata.toLocal8Bit();
char *cdata = local8Bit.data();@
Would be a more clean solution but you should rather use something like
Hope it helps