accessing C string within QString



  • Hi, all -

    I'm using the output of a QSerialPort read to update a QPlainTextEdit. The serial port read uses a standard C char *, while the QPlainTextEdit expects a QString. I'm trying to find an efficient way to do this (hopefully not having to copy the buffer from char * to QString).

    Is there some way for me to access the C string within the QString as the target of the read()?

    If I'm "doing this wrong" feel free to so inform me.

    Thanks...


  • Qt Champions 2016

    Hi
    Normally its
    QByteArray QIODevice::readAll()

    so where does the char * come from?


  • Qt Champions 2016

    Anyway, QString have
    QString(const char *str)
    so it can be constructed directly from char *



  • I'm using this call.

    I haven't done much with QByteArrays; do they efficiently convert to QStrings? I'm communicating with a primitive device whose communications is a bit erratic, so I need to move data out of the input buffer as quickly as possible.


  • Qt Champions 2016

    @mzimmers
    Hi
    Well you can do
    QString s_data = QString::fromLatin1 fromAscii(data.data()); // data being ByteArray, ( fromAscii is obsolete. sorry)
    so i think they offer better handling of utf8 etc but i do not think its faster than
    constructing a QString from char * buffer.

    so if the read() works fine then when ready, make sure its 0 terminated and
    simply do
    PlainTextEdit->append( QString( mycharbuffer ) ) ;


  • Qt Champions 2016

    Use this instead. Then use QString::fromLatin1 assuming that's the encoding your device uses.

    I haven't done much with QByteArrays; do they efficiently convert to QStrings?

    That would depend what is in the byte array, but generally not "very efficiently". Strings are encoding aware, while array of bytes is just that - an array of bytes.



  • @mzimmers: Don't worry about conversion speed, with serial ports, the longest time is to
    wait for the characters to arrive.

    You didn't tell us the bitrate you are using, but I guess it's in the upper micro- or lower millisecond range for one char to come in.

    Converting one character from char to QChar (a QString is an array of QChars) should take max. lower microsecond range.

    The fastest possible conversion is fromLatin1(), if you receive pure ASCII or Latin-1 encoded strings, you can use this. In case you have to convert fromUtf8(), it will be a bit slower, but trust me: you will not feel a difference.



  • @kshegunov thanks. I was hoping for some way of avoiding the copy entirely (like port->read(myQString->someMagicAccessToCString) but I guess that's not possible.

    Anyway, as aha pointed out, it probably doesn't matter. My desktop is arbitrarily fast compared to the serial port.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.