Important: Please read the Qt Code of Conduct -

Qstring to const char*

  • Hello.
    I'm trying to use QList to send data via serial port.

    @QList<QString> command;

    command << " -60\n"
    << "ant.holding\n";@

    How should I convert qstring to send data with QIODevice::write(const char * data)?
    Thanks fot help.

  • Qt Champions 2017

    @QString sdata;
    char *cdata = sdata.toLocal8Bit().data();@

  • First you need to join the strings together into a single string object.

    Method 1: Straightforward concatenation
    QString result;
    foreach (QString s, command)
    result += s;

    Method 2: Use QStringList

    QStringList commandSL(command);
    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!

  • Lifetime Qt Champion


    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 =;@

    Would be a more clean solution but you should rather use something like


    Hope it helps

Log in to reply