Solved QVariant as uint16_t type
-
Hello!
How do I create aQVariant
with a data typeuint16_t
?
If I understand correctly, I needQMetaType::UShort
(unsigned short
like, the same thinguint16_t
).
But now I'm creating aQVariant
this wayQVariant(QVariant::Type::UInt) vect; //There is not what I need here.
And how do I determine the size of the data stored in the
QVariant
?
Is this the right way?QMetaType::sizeOf(vect.type());
-
Since
QVariant
doesn't have aQVariant::Type
foruint16_t
you need the other constructor that takes theQMetaType::Type
(assumingunsigned short
anduint16_t
are the same thing on your platform):QVariant vect(QMetaType::UShort, nullptr);
Alternatively you can construct the variant from a value:
QVariant vect = QVariant::fromValue((uint16_t)0);
-
@Chris-Kawa thank you!
Can you please suggest how to convert the QVariant into an array of bytes (uint8_t)?
I found the perfect solutionunion { float data; uint8_t bytes[4]; } r2b; //result to byte array
But the data can be of any type (depending on the QVariant), accordingly, the size of the array can also be different.
Is it possible to somehow create a variable of the same type as the QVariant value? -
I found the perfect solution
It's far from perfect, I assure you ;)
Not a direct response, but I'm guessing your next question after that would be "how do I convert an array of bytes back into QVariant?" and then "how do I know which type of variant is encoded in an array of bytes?" and then "Why when I convert and save bytes on platform X and then read and convert back on platform Y the value is different?" and then "how do I know if the bytes I read in program version X are in the same format/version as the ones I wrote in program version Y?".
All in all this is a topic of data serialization and Qt has specialized classes to deal with all this complexity. See QDataStream for details. It lets you serialize QVariant (provided that serialization is implemented for the types inside) to a QByteArray and back in a consistent, platform independent and versioned way.
-
@Chris-Kawa said in QVariant as uint16_t type:
but I'm guessing your next question
No, I wanted to know just that. I do with templates
template <class T> union res_to_byte{ T data; uint8_t bytes[sizeof(T)]; }; //result to byte array
But I do not know what to put here
res_to_byte</**here**/> r2b;
-
The variant can hold data of different sizes. Templates are compile time so the size needs to be constant. The best you can do is assume a size of the biggest type you support. You can for example create a union of all supported types and get a sizeof of that. This is kinda what QVariant does inside so you'd be re-inventing a wheel a little, but that's one way to do it.