使用串口调试将从TextEdit中读取的中文,写入串口,需要进行编码转换,代码如下:
void SerialDemo::writeSerialPort()
{
QString user_input = NULL;
char * to_send = NULL;
int ret = 0;
int trytimes = 0;
size_t char_count = 0;
to_send = (char *)malloc(1024);
user_input = ui->txTextEdit->toPlainText();
qDebug()<<"1.txTextEdit:"<<user_input;
strcpy(to_send,user_input.toStdString().data());
char_count = user_input.toAscii().length();
qDebug()<<"2.user_input length:"<<char_count;
qDebug()<<"3.to_send:"<<to_send;
ret = write(di_s4b_comfd,to_send,char_count);
writeCount += ret;
qDebug()<<"4.in writeSerialPort the writeCount:"<<writeCount;
delete(to_send);
}
可以发往windows显示中文
PS:忘记说编码问题,linux下需要设置CSTRING编码为UTF-8,QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
此外如果要从QString直接写入特定中文字符串到串口,需要QString::fromUTF8("中文");再进行其它一样的处理。