Skip to content
All articles

C++ · Qt · Architecture

Reflective binary serialization with C++ and Qt

Use Qt property metadata to encode, decode, and edit changing message types without maintaining a serializer for every class.

By Qmob engineering team · December 1, 2026 · 5 min read

Reflective binary serialization with C++ and Qt: Q_PROPERTY, QMetaObject, and QDataStream

When a binary message gains a field, a handwritten serializer needs a matching write, read, length calculation, and often a test-client control. Forget one and the class and wire format diverge. The motivation for reflection is to make the message's property declarations the single place where its shape is maintained.

That choice has alternatives. Handwritten QDataStream operators give precise control and minimal runtime dispatch, but repeat field lists. Protocol Buffers defines a separate .proto schema and generates readers, writers, and message classes; it is a strong choice when cross-language contracts and schema evolution matter. MessagePack specifies a compact binary format for values and containers, but an application still has to decide how its C++ classes map to those values. Qt reflection is attractive when the application already uses QObject properties and controls both ends of a compact, fixed protocol. It removes per-message serialization code, not the need for a wire contract.

One QObject property model feeds binary encoding, decoding, and the mock-client editor
The property model is reused by three features; no separate field list is maintained for each one.

Declare the shape once

The design has two layers. BaseStruct inherits QObject and owns the generic length() calculation plus the stream operators. BaseMessage inherits BaseStruct and declares the common header: unit code, constant opcode, and computed length. Concrete message classes add their payload properties. Because Qt exposes inherited properties through the concrete object's QMetaObject, a single traversal sees header and payload together. The abbreviated declarations below show the structure; names and types are illustrative.

class BaseStruct : public QObject {
    Q_OBJECT
public:
    Q_INVOKABLE explicit BaseStruct(QObject *parent = nullptr);
    quint16 length() const;
};

class BaseMessage : public BaseStruct {
    Q_OBJECT
    Q_PROPERTY(UnitCode unitCode MEMBER unitCode NOTIFY unitCodeChanged)
    Q_PROPERTY(Opcode msgOpcode MEMBER msgOpcode CONSTANT)
    Q_PROPERTY(quint16 length READ length NOTIFY lengthChanged)
public:
    UnitCode unitCode;
    const Opcode msgOpcode;
    Q_SIGNAL void unitCodeChanged(UnitCode);
    Q_SIGNAL void lengthChanged(quint16);
};

QDataStream &operator<<(QDataStream &, const BaseStruct &);
QDataStream &operator>>(QDataStream &, BaseStruct &);

Q_OBJECT makes each class visible to Qt's meta-object system. A small declaration macro can add a Q_PROPERTY alongside a C++ member and change signal. A concrete message then needs only its fields and constructor:

#define MESSAGE_FIELD(Type, Name, Initial) \
    Q_PROPERTY(Type Name MEMBER Name NOTIFY Name##Changed) \
public: \
    Type Name = Initial; \
    Q_SIGNAL void Name##Changed(Type);

class StatusMessage : public BaseMessage {
    Q_OBJECT
    MESSAGE_FIELD(quint8, deviceId, 0)
    MESSAGE_FIELD(float, temperature, 0.0f)
public:
    Q_INVOKABLE explicit StatusMessage(QObject *parent = nullptr);
};

At runtime, metaObject()->propertyCount() includes inherited properties. The implementation starts at index 1 to skip QObject::objectName, then visits the remaining properties in meta-object order. Each QMetaProperty exposes its name, type, value, and writability. A dispatch based on that metadata handles supported integer and float types, 16-bit wire enums, nested BaseStruct pointers, and lists of such pointers. The base message also exposes an opcode and a computed 16-bit length as header properties.

The write path uses little-endian QDataStream with single-precision floats. For supported numeric types it calls typed stream operators, so the configured byte order applies. Enum values are explicitly converted to qint16. The remaining primitive fallback writes raw bytes; that path requires a deliberately restricted type set because raw data is not endian-converted.

for (int i = 1; i < object.metaObject()->propertyCount(); ++i) {
    const QMetaProperty field = object.metaObject()->property(i);
    if (field.isEnumType()) {
        stream << qint16(field.read(&object).toInt());
    } else if (field.metaType().id() == QMetaType::Float) {
        stream << field.read(&object).toFloat();
    }
    // Other supported types, nested objects, and list counts follow.
}

Two passes, one deterministic layout

The first traversal writes fields in property order. A nested object is encoded recursively at its position; a list writes only its one-byte count. The second traversal appends each list's elements, again in property order. Decoding mirrors these two traversals: it remembers list counts, reads ordinary fields and nested objects, then constructs and fills list elements.

Binary layout with opcode, length, nested fields and list count followed by list elements
Conceptual layout for a message with one nested object and a two-element list; actual fields depend on the message class.

This order is part of the protocol. Reordering or inserting a property can change the bytes even though the serializer needs no edits. Both endpoints therefore need compatible class definitions. Reflection removes duplicate code; it does not automatically provide field tags, unknown-field preservation, or schema migration.

For pointer fields, the reader looks up the registered pointer type's QMetaObject, calls a Q_INVOKABLE constructor when needed, attaches the new object to its parent, and recursively decodes it. For lists it constructs each registered element type, replaces the previous list, and deletes previously owned elements after a successful replacement. The reader checks stream status, constructor and property-write failures, the constant opcode, and the computed length against the received length. The writer rejects a list whose count exceeds the format's quint8 capacity.

The same metadata drives a mock client

The desktop test client walks the same properties to create editors: combo boxes for enums, checkboxes for booleans, spin boxes for numbers, and nested groups for objects and lists. Selecting a message changes the form; editing a field changes the object that will be serialized. This makes structural changes visible without building a custom form for each message.

Mock client showing a property-driven message form and response area
The property-driven mock client exposes message fields for editing and displays decoded responses.

What the design protects—and what still needs care

The implementation has tests for integer and enum round trips, nested objects and lists, repeated list decoding, wrong opcodes, missing invokable constructors, truncated input, incorrect lengths, and lists above 255 elements. Those checks are valuable, but they are not a substitute for a complete protocol boundary.

  • Supported types: the raw-byte fallback should become an explicit allowlist or an error. Its bytes bypass QDataStream conversion, and an unsupported QVariant representation is not a stable wire format.
  • Nulls and sizes: the encoder and length calculator dereference nested pointers. Define whether null is legal and encode its presence if so. Accumulate lengths in a wider type before checking the 16-bit limit.
  • Failure atomicity: a failed read can leave ordinary fields or nested objects partially updated. Decode into a temporary object, or document that callers must discard a failed target.
  • Compatibility: pin the QDataStream version, document the property order and field widths, and add golden-byte and cross-version tests before changing messages. Bound total input size and nesting depth for untrusted data.

The result is a useful engineering tradeoff: one property declaration can drive serialization, deserialization, and inspection, while the protocol remains explicit enough to test. Choose it when reducing message-class maintenance matters and the participating endpoints can evolve together. Choose a schema-driven format when independent producers, long-lived compatibility, or cross-language consumers are the primary requirement.

References: Qt meta-object system, Qt property system, QDataStream, Protocol Buffers overview, MessagePack specification.

Let's discuss your engineering challenge.

Tell us about your product, technical constraints, and goals. We'll help identify the right starting point.

Discuss Your Project