External vs internal declaration of QByteArray

浪尽此生 提交于 2019-12-11 10:26:59

问题


I have currently some problems with the QSerialPort: When I am using the function from an example which looks like

QKeyEvent *e;
emit getData(e->text().toLocal8Bit());
connect(console, SIGNAL(getData(QByteArray)), this, SLOT(writeData(QByteArray)));
void MainWindow::writeData(const QByteArray &data)
{
    qDebug() << "Data is to write: " << data;
    serial->write(data);
}

then the receiving device can work with the data. But when I change the function writeData() to

void MainWindow::writeData(const QByteArray &data)
{
    QString a = "Q";
    QByteArray b = a.toLocal8Bit();
    serial->write(b);
}

the receiving device can not work with the received data. Where is the difference between those two approaches?
Update: I found out that apparently the data is only usefully transferred if I press Enter after typing the letters. Somehow the '\n' gets lost in the conversion from QString to QByteArray. How can I keep it?


回答1:


you should add an enter to your Qstring like this

QString a = "Q\x00D";




回答2:


In the example you have given, there is no "\n" in the QString! It is not getting lost, it is not there in the first place.

If a newline is necessary, then construct the String as QString a = "Q\n".

You can also construct the QByteArray directly from a character array rather than going through a char array -> QString -> QByteArrray conversion sequence, like so:

QByteArray b("Q\n");

EDIT: I realized that your contrived example where you are just sending the letter "Q" is probably a debug attempt, not your real code. In reality, you're getting data in as a QByteArray from some other signal that is emitting a QByteArray. That QByteArray that you are receiving must not include the newline character in it. If you are reading from a file or user input, then that is normal. Most readline-like functions strip off the trailing newline. If it is always necessary to have a newline, you can simply do something like this in your WriteData method:

void MainWindow::writeData(const QByteArray &data)
{
    serial->write(data);
    serial->write("\n");
}

If sometimes the passed-in QByteArray has a newline at the end and sometimes not, and your receiving device cannot handle redundant newlines, then you'd need to check whether data ends with a newline and only write the "\n" if it does not.




回答3:


what if you make the QByteArray like this

QByteArray b(&a);


来源:https://stackoverflow.com/questions/33387148/external-vs-internal-declaration-of-qbytearray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!