I am going to save a struct in a binary file and load it later on. I found that one way is to use QVariant
. Here is a simplified Qt Widget Application example that I have created. But when I run it the binary file remains empty. Could you please help me with that. Also, Is there a better method to do such a thing?
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFile>
#include <QFileDialog>
#include <QDataStream>
#include <QString>
#include "mystruct.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
/* create an object of the struct */
myStruct * aStruct = new myStruct;
aStruct->myStringVar = QString("aaaaa");
/* put the object in QVariant */
QVariant aVariant;
aVariant.setValue(aStruct);
/* save the QVariant to binary file */
QFile myFile("myFile");
QDataStream save(&myFile);
save.setVersion(QDataStream::Qt_4_6);
save << aVariant;
myFile.close();
/* load the QVariant from binary file */
QDataStream load(&myFile);
load.setVersion(QDataStream::Qt_4_6);
QVariant theVariant;
load >> theVariant;
QString theVar = theVariant.value<myStruct*>()->myStringVar;
myFile.close();
}
MainWindow::~MainWindow()
{
delete ui;
}
mystruct.h:
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
#include <QMetaType>
#include <QString>
struct myStruct
{
QString myStringVar;
};
Q_DECLARE_METATYPE(myStruct*)
#endif // MYSTRUCT_H
Comment: As a reference, this link shows a similar problem, but I could not understand/implement the suggestions correctly. For example, I tried to define a new operator, as it is explained here, but it did not work.