Saving Qlist data in a mysql database
-
This is my data setup (simplified):
Class Animation
{
...
typedef struct
{
QImage I;
QTime ts;
} Anim_t;
...
};QList<Animation::Anim_t> Animations;
The QList can have between 0 and 10 items in it at any one time.
The QImage's are small 512x512 pixels.
I would like to save the whole Qlist in a mysql table as a single entity.
Has anyone got a suggested solution for this problem ?Thanks
-
Hi,
What do you mean by "as a single entity" ? The whole QList as one binary blob ?
If so you can use QDataStream to serialize your list into a QByteArray and store that array as a blob.
-
Please take a look at the examples on how to use QDataStream. It clearly shows how to put a QString into a QIODevice (in this case a QFile, but for QByteArray/QBuffer it's the same).
-
@SMF-Qt
Be aware that in order to stream yourstruct
to/from aQDataStream
you will need it to implement<<
&>>
operators (not hard, just needs to be done).Note also that the image will be streamed as a PNG image (https://doc.qt.io/qt-5/qimage.html#operator-lt-lt-21), you don't have a choice over this, so that needs to be acceptable to you.
-
Tried this for the << operator:
QDataStream &operator<<(QDataStream &stream,const Anim_t &anim) { stream << anim.ts.msecsSinceStartOfDay() << anim.I; return stream; }
Got this error, what have I missed ?
anim.h:35:15: error: 'QDataStream& Anim::operator<<(QDataStream&, const Anim::Anim_t&)' must have exactly one argument
35 | QDataStream &operator<<(QDataStream &stream,const Anim_t &anim) -
-
It must be a free function, if it's a member of your struct then you have to remove
const Anim_t &anim
-
Ok implimented operators as free functions and everything now compiles, however on running the application the QByteArray is empty (example with one element in QList):
...
QDataStream &operator<<(QDataStream &stream, const Anim::Anim_t &anim)
{
stream << anim.ts.msecsSinceStartOfDay() << anim.I;
return stream;
}QDataStream &operator>>(QDataStream &stream, Anim::Anim_t &anim)
{
int t;
stream >> t >> anim.I;
anim.ts = QTime::fromMSecsSinceStartOfDay(t);
return stream;
}...
QByteArray array; QDataStream stream(array); for(int i=0;i<Animations.size();i++) { stream << Animations.at(i); } QByteArray tmp=qCompress(array,9); fprintf(stderr,"Binary Blob Animations (%lld) size %lld compressed size %lld\n",Animations.size(),array.size(),tmp.size());
...
Binary Blob Animations (1) size 0 compressed size 4
Any suggestions ?
Thanks -
@SMF-Qt said in Saving Qlist data in a mysql database:
QDataStream stream(array);
Please read: https://doc.qt.io/qt-5/qdatastream.html#QDataStream-3
"Use QDataStream(QByteArray*, int) if you want to write to a byte array." -
@SMF-Qt Then also please mark this topic as solved, thx.
-
If I may, there's no need for the loop, you should be able to directly stream the list object and not go manually with that loop.