PDA

View Full Version : UI text to char



iasdev
1st February 2016, 16:10
Hello newbie here.

I am having trouble converting a simple text within the UI to Char. My goal is to submit text in the UI which will be sent to a usb to rs 485.

I have no trouble sending text directly from within the code, but I would like to send my component different commands from within the UI on the fly.

Here is the snippet of code giving me problems.


QString Motor_Command_;


Motor_Command_ = ui->MotorCommandText->toPlainText().toLocal8Bit().constData();



char TxBuffer[] = {Motor_Command_};


The error I get:

error: cannot convert 'QString' to 'char' in initialization
char TxBuffer[] = {Motor_Command_};
^

anda_skoa
1st February 2016, 17:37
You are doing a double conversion there, potentially lossy.

First you encode the QString returned by toPlainText() with the 8-bit codec used for local encoding (toLocal8Bit()), then you convert back to QString using UTF-8 (when assigning to the QString variable).

If your low-level API required a char*, then first get the encoded form as a QByteArray and then send its constData().

E.g.


const QByteArray data = ui->MotorCommandText->toPlainText().toLocal8Bit();
low_level_write(data.constData(), data.size());


Cheers,
_