Search code examples
c++qtserializationbinary-dataqvariant

How can I get the raw binary content from an arbitrary typed QVariant into a QBytearray?


Problem

I have an interface which gives me a QVariant of an arbitrary type. I need to convert the data content in this variant to a raw binary QByteArray:

QVariant result = myQVariantReturningMethod(type arg, type arg2);
QByteArray rawResult = ?;

Background

The resulting QByteArray is sent over Canbus. Depending on its size, it is transmitted in several can frames or in a single one. The can bus interface for sending frames takes a QByteArray as input. Based on additional information, the receiver of the can frames knows how to parse the incoming stream of can frames.

What I tried so far

I tried several approaches

  • Using a QDataStream to get the data into the array. However the serialization works in an unpredictable way, where I always get additional information about the type itself in the resulting array, depending of the implementation of the <</>> operators for the type.
  • Using toString().toStdString() of the QVariant, resulting in a casted value, not the actual binary raw data which is not what I want.
  • Using toBytearryay(), resulting in the same.

I do not care whether an stl way or a qt way is a possible approach to the problem. However, It has to be c++11-compatible


Solution

  • It turns out, that QVariant has an undocumented method constData() which gives exactly the result I want to have: A pointer to the internally stored data of the QVariant. Together with QMetaType::sizeOf(), this is exactly what is needed to write all the data into a QByteArray.

    I found that method documented in the documentation of Qt 6.0 and found it as well working with my Qt 5.12.7, despite not being described in the corresponding documentation.