i have a very simple question here, How can i send a string with
tcpserver->write(string);
I tried:
tcpserver->write("string")
and it works, but if i want to input a string in there, i get a "no matching function to call to 'QtcpSocket::write(QString)'"
error,
so i tried converting the string to "data" and then send it, but i got a ton of errors...
And my question is: How can i easly send a string thru my tcpserver?
(I should also mention, that i am very new to programming)
You need to convert string to QByteArray, for example:
tcpserver->write(string.toLocal8Bit());
tcpserver->write(string.toUtf8());
Try tcpserver->write((const char *)string.data(), string.length()*sizeof(QChar));
QTcpSocket has 3 overloads for write () function
qint64 write (const char *data);
qint64 write (const char *data, qint64 len);
qint64 write (const QByteArray &data);
So Convert QString to any of them. Just try
tcpserver->write (string.toLatin1 ());
Related
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?
you should add an enter to your Qstring like this
QString a = "Q\x00D";
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.
what if you make the QByteArray like this
QByteArray b(&a);
I am trying to setup two way communication via the QUdpSocket. I am trying to send a struct consisting of a C++ Eigenvector and a double. I have tried serializing into a QByteArray as follows:
MyStruct toSend;
QByteArray buf;
QDataStream s(&buf, QIODevice::WriteOnly);
if (false) s.setByteOrder(QDataStream::LittleEndian);
std::string vec_str = eigenToStr(toSend.vec);
s << (double)toSend.test1 << QString(vec_str.c_str());
Where eigenToStr() converts the Eigenvector to a string.
However, I am unable to read the message on the other end. When I convert back to a string before sending the QByteArray, I get #ffffff. So I assume it's an issue with the QByteArray/QDataStream conversion.
I would appreciate any suggestions as to how I might serialize my struct so that I can send it via UDP.
Thanks!
QByteArray and QDataStream cooperate very well:). If you really want write the raw data to QDataStream , please use the method :
int QDataStream::writeRawData(const char * s, int len)
And personally I prefer to overload << way to write user data to QDataStream, such as
QDataStream& operator <<(QDataStream& out,MyStruct & data)
Then probably code looks as :
MyStruct toSend;
QByteArray buf;
QDataStream s(&buf, QIODevice::WriteOnly);
if (false) s.setByteOrder(QDataStream::LittleEndian);//false ?
s << toSend;
void GenerateDecryptedData("/home/merve/merve.enc", "/home/merve/merve.dec","dEneMe!1234");
I want to call my function like dEneMe!1234.
void GenerateDecryptedData(const char* pathToEncryptedFile,
const char* pathToDeccryptedFile,
std::string Pwd);
But when I wrote the function prototype like this, I'm taking string has not been declared- error! How can I take my password in string type?
You need the string header at the top of your source file: #include <string>. I'd consider Googling error messages more often. :)
string header - http://www.cplusplus.com/reference/string/
cstring header - http://www.cplusplus.com/reference/cstring/
What's wrong with:
void GenerateDecryptedData(const char* pathToEncryptedFile, const char* pathToDeccryptedFile, const char* Pwd);
How Can I deserialize the output QVariant to std::string without using QT.
by reqs, My program could not include a Qt.
QVariant.toString().toStdString();
Example.
file.ini (write with QSetting)
..
ID="\x1\0\0\0\xd0\x8c\xd9\xec\xfb*"
profile_program /* Pseudo Code */
int main ()
{
void* IDQt =getIDFromIniFile("file.ini");
std::string myId = convertID(IDQt);
process(myID);
}
Look in the sources, probably src/corelib/kernel/qvariant.cpp for QDataStream& operator<<(QDataStream&, const QVariant&). That way you'll know what gets written during serialization.
Once you do, you'll see that the operator<< calls QVariant::save(QDataStream&). What's written is as follows:
quint32 QVariant::type()
quint8 QVariant::isNull()
if type()==UserType
QString MetaType::typeName(userType())
end
if the variant is not valid
QString empty
else
-- MetaType::save(...)
end
You need to drill down into QString and QMetaType to figure out how those are serialized.
I would like to dip into Google's protocol buffers in Qt development, but I am having trouble figuring out how to incorporate them best.
Ultimately, I want to send with QUdpSocket and QTcpSocket using protocol buffers.
What is the best method for going between a protocol buffer message to sending the data over a socket (QByteArray) and then back again at the other side?
Creating a QByteArray from a protobuf object:
Person person; // a protobuf object
person.set_id(123);
person.set_name("Bob");
person.set_email("bob#example.com");
std::ostringstream out;
person.SerializeToOstream(&out);
QByteArray byteArray(out.str().c_str());
sendSerializedPersonOverQTcpSocket(byteArray);
Reading back a protobuf object from a QByteArray:
QByteArray byteArray = readSerializedPersonFromQTcpSocket();
Person person;
if (!person.ParseFromArray(byteArray, byteArray.size())) {
std::cerr << "Failed to parse person.pb." << std::endl;
}
Instead of:
std::ostringstream out;
person.SerializeToOstream(&out);
QByteArray byteArray(out.str().c_str());
you can also write:
QByteArray byteArray(person.SerializeAsString().c_str());
EDIT: Above two gives the same result, but I'm not sure wether it's correct. This one seems to work better:
QByteArray byteArray(QString::fromStdString(person.SerializeAsString()));
EDIT2: OK, now I know how it works: first two ways are wrong if there are \0 char in serialization - everything after it it's then lost. To correct it one can write:
QByteArray byteArray(person.SerializeAsString().c_str(), person.ByteSize());
Using the code below is really dangerous
std::ostringstream out;
person.SerializeToOstream(&out);
QByteArray byteArray(out.str().c_str());
sendSerializedPersonOverQTcpSocket(byteArray);
You can find a good explanation here In protobuf-c, can optional uint32 variable have value 0
A right way to create a QByteArray from a protobuf message is
QByteArray byteArray;
byteArray.resize(message.ByteSize());
message.SerializeToArray(byteArray.data(), byteArray.size());
#James: You can use ParseFromArray(), for example, as below: (Please note that ParseFromArray() is available only on proto-buf-lite versions of the libs).
void convertQByteArrayToUser(QByteArray& aByteArray)
{
com::your::name_space::User user;
if(!user.ParseFromArray(aByteArray.data(), aByteArray.size()))
{
//could not parse
}
else { //yayyyyy
if(user.has_userid())
{
//...
}
}
}