Search code examples
c++qtqbytearray

Custom type to QByteArray


I have a custom struct like this:

struct aReminderStruct{
    QString name;
    QDate date;
    QTime time;
    QString reminderText;
};

aReminderStruct myNewReminder;

How can I convert myNewReminder to QByteArray once filled with data?


Solution

  • You need to define custom datastream operators like that:

    struct aReminderStruct{
        QString name;
        QDate date;
        QTime time;
        QString reminderText;
    };
    
    // you need this if you want to use your type with QVariant
    Q_DECLARE_METATYPE(aReminderStruct)
    
    QDataStream &operator<<(QDataStream &out, const aReminderStruct &a)
    {
        out << name << date << time << reminderText;
        return out;
    }
    
    QDataStream &operator>>(QDataStream &in, aReminderStruct &a)
    {
        in >> name >> date >> time >> reminderText;
        return in;
    }
    

    ...

    int main(...)
    {
        QApplication app(...);
    
        qRegisterMetaTypeStreamOperators<aReminderStruct>("aReminderStruct");
         ...
        aReminderStruct a;
        a = ...;
    
        QByteArray data;
        QDataStream ds(&data, QIODevice::ReadWrite);
        ds << a;
    }