convert QByteArray to QString is empty - qt

I use QTcpSocket::readAll() got a QByteArray. However when I used QString::fromUtf8() to convert it to QString, I got a empty QString.
QByteArray ba;
QDataStream in(&ba,QIODevice::ReadWrite);
in << socket->readAll();
QByteArray request = ba;
qDebug() <<"ba:" << ba; // right message
Then:
QString request = QString::fromUtf8(ba); // request is empty
QString request = QString(ba) //also empty

Maybe your bytearray has different text encoding (cyrillic - win1251 or DOS - cp866). For converting bytearray with specific encoding into string use QTextCodec
QByteArray ba("abcd");
QTextCodec *codec = QTextCodec::codecForName("CP1251");
QString str = codec->toUnicode(ba);

Your message is not coded in utf8, maybe GB18030.
In your main function, you must set your codec.
QTextCodec *gb = QTextCodec::codecForName("gb18030");
QTextCodec::setCodecForLocale(gb);
Then you can process the message(I am using Qt4).
QByteArray ba = s->readAll();
QString request = QString::fromLocal8Bit(ba.data(),ba.size());

...
QJsonDocument doc(jobject);
ByteArray arr = doc.toJson();
//Just cast
QString result = static_cast<QString>(doc.toJson());

Related

QByteArray to int always give 0

I try to send data throw qtcpsocket and use QByteArray. I send previosly size of data and try convert to int like this QByteArray to Int conversion.
But always get 0. Code convertion example:
QString ss = "bca";
int aaa;
QByteArray b;
QDataStream stream(&b, QIODevice::ReadWrite);
stream << ss.toUtf8().size();
stream >> aaa;
In this example aaa is always 0, but ss.toUtf8().size() isnt. What im doing wrong?
QString ss = "bca";
int aaa;
QByteArray b;
QDataStream stream(&b, QIODevice::ReadWrite);
stream << ss.toUtf8().size();
stream.device().seek(0); // add this code
stream >> aaa;
The inner pointer of QByteArray is at the end, so nothing can be read.

How can I get convert wstringstream to char*?

how convert wstringstream to char* ?? (Language c++)
I need this conversion to use the function writeRawData of the qdatastream.h library.
Thank you very much!!
You have to use wstringstream::str() to retrieve the content of the stream.
And then depending on your need you can either convert it to a QString so that the QDataStream can handle the string for you or just write the bytes of the wstring:
void f(wstringstream &stream, QDataStream &qstream)
{
wstring content = stream.str();
QString str = QString::fromStdWString(content);
qstream << str;
}
void g(wstringstream &stream, QDataStream &qstream)
{
wstring content = stream.str();
qstream.writeRawData(static_cast<const char *>(content.c_str()), content.length() * sizeof(wchar_t));
}
wstringstream is a basic_stringstream, you could extract line, char, text from it
look at that http://www.cplusplus.com/reference/sstream/wstringstream/
and you could retreive one example from that http://www.cplusplus.com/reference/sstream/basic_stringstream/str/

store exact cv::Mat image in sqlite3 database

is there any way to store exact cv::Mat format data in sqlite3 using Qt.. as i will be using the same cv::Mat format in future..
i tried converting image to unsigned char* and them storing it.. but this didn't worked for me.. any other technique ??
You can serialize cv::Mat to QByteArray (see kde/libkface):
QByteArray mat2ByteArray(const cv::Mat &image)
{
QByteArray byteArray;
QDataStream stream( &byteArray, QIODevice::WriteOnly );
stream << image.type();
stream << image.rows;
stream << image.cols;
const size_t data_size = image.cols * image.rows * image.elemSize();
QByteArray data = QByteArray::fromRawData( (const char*)image.ptr(), data_size );
stream << data;
return byteArray;
}
Then store to DB.
To convert from QByteArray after reading from DB:
cv::Mat byteArray2Mat(const QByteArray & byteArray)
{
QDataStream stream(byteArray);
int matType, rows, cols;
QByteArray data;
stream >> matType;
stream >> rows;
stream >> cols;
stream >> data;
cv::Mat mat( rows, cols, matType, (void*)data.data() );
return mat.clone();
}
It works for me.

Qt array QString

I get result from db by selectall query and I want save result in array and send it by socket.
db.open();
QSqlQuery *selectall = new QSqlQuery(db);
selectall->prepare("select * from phone_table");
selectall->exec();
selectall->first();
QString result;
QByteArray arrayresult;
int index = 0;
while (selectall->next())
{
index += 1;
// qint16 id = selectall->value(0).toString();
QString name_ = selectall->value(1).toString();
QString surname = selectall->value(2).toString();
QString phone_number = selectall->value(3).toString();
result = "*"+ name_+"*"+surname+"*"+phone_number;
arrayresult[index] = result;
}
I get this error binary '=' : no operator found which takes a right-hand operand of type 'const char [16]'
You are trying to set a QByteRef to a QString.
I think you may want a QList and to arrayresult.append(result).
Or else if you want one QByteArray with the concat of all results use arrayresult+= result.
You may build the QString you want to initialize QByteArray. To then convert from QString to QByteArray, you can do
QByteArray array_ = string_.toLatin1();
if encoding is Latin1.
You may alternatively use append
QByteArray & QByteArray::append ( const QString & str )
This is an overloaded function.
Appends the string str to this byte array. The Unicode data is
converted into 8-bit characters using QString::toAscii().
If the QString contains non-ASCII Unicode characters, using this
function can lead to loss of information. You can disable this
function by defining QT_NO_CAST_TO_ASCII when you compile your
applications. You then need to call QString::toAscii() (or
QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
explicitly if you want to convert the data to const char *.
append is doing the same as + operator.
You can do the following with the toLatin1() function of the QString.
// ...
QString result = QString( "*%1*%2*%3" ).arg( name_ )
.arg( surname )
.arg( phone_number );
QByteArray resultArray = result.toLatin1();
// Or ...
// QByteArray resultArray = result.toLocal8Bit();
// QByteArray resultArray = result.toUtf8();
And you shall use a QList< QByteArray > for containing the results, or you can just append the last result item to your final result object.

Qt QList<QString> serialization for database

I have a QList list. I want to insert it on the database. I didn't find any serializer method after some googling. If there any method / idea to serialize the list data for database?
How about using QStringList instead of QList<QString> -
QStringList numberList_; // instead of QList<QString>, use this
QString myString1 = "Hello";
QString myString2 = "World";
numberList_ << myString1;
numberList_ << myString2;
QByteArray byteArray;
QBuffer buffer(&byteArray);
QDataStream out(&buffer);
out << numberList_;
Probably QList<QString> should also work in place of QStringList. If it doesn't, well, you can convert it pretty easily to QStringList.
QDataStream, QBuffer,
QByteArray and QStringList reference.
Here is another option that is a bit more succinct:
QString serialize(QStringList stringList)
{
QByteArray byteArray;
QDataStream out(&byteArray, QIODevice::WriteOnly);
out << stringList;
return QString(byteArray.toBase64());
}
QStringList deserialize(QString serializedStringList)
{
QStringList result;
QByteArray byteArray = QByteArray::fromBase64(serializedStringList.toUtf8());
QDataStream in(&byteArray, QIODevice::ReadOnly);
in >> result;
return result;
}

Resources