Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the QDataStream << and >> operators for a user-defined type

I have a an object I'd like to be able to read and write to/from a QDataStream. The header is as follows:

class Compound
{
public:
    Compound(QString, QPixmap*, Ui::MainWindow*);
    void saveCurrentInfo();
    void restoreSavedInfo(QGraphicsScene*);

    void setImage(QPixmap*);

    QString getName();

private:
    QString name, homeNotes, addNotes, expText;
    Ui::MainWindow *gui;
    QPixmap *image;        

    struct NMRdata
    {
        QString hnmrText, cnmrText, hn_nmrText, hn_nmrNucl, notes;
        int hnmrFreqIndex, cnmrFreqIndex, hn_nmrFreqIndex,
        hnmrSolvIndex, cnmrSolvIndex, hn_nmrSolvIndex;
    }*nmr_data;

    struct IRdata
    {
        QString uvConc, lowResMethod,
            irText, uvText, lowResText, highResText,
            highResCalc, highResFnd, highResFrmla,
            notes;
    int irSolvIndex, uvSolvIndex;
    }*ir_data;

    struct PhysicalData
    {
        QString mpEdit, bpEdit, mpParensEdit, bpParensEdit,
            rfEdit, phyText, optAlpha,
            optConc, elemText, elemFrmla,
            notes;
        int phySolvIndex, optSolvIndex;
    }*physical_data;   
};

For all intents and purposes, the class just serves as an abstraction for a handful of QStrings and a QPixmap. Ideally, I would be able to write a QList to a QDataStream but I'm not exactly sure how to go about doing this.

If operator overloading is a suitable solution, would writing code like

friend QDataStream& operator << (QDataStream&,Compound) { ... }

be a potential solution? I'm very open to suggestions! Please let me know if any further clarification is needed.

like image 483
Alex Wood Avatar asked Mar 18 '10 20:03

Alex Wood


2 Answers

I think you've answered your own question! The stream operator

QDataStream& operator<<( QDataStream&, const Compound& )

will work fine. In the implementation you just use the existing stream operators on QDataStream to serialise the individual bits of your Compound. Some Qt classes define non-member QDataStream operators too. QString is one and so is QList so it looks like you're sorted!

like image 179
Troubadour Avatar answered Nov 15 '22 01:11

Troubadour


If you want to overload the "extract" operator >>, your signature must be:

QDataStream & operator >> (QDataStream & in, MyClass & class);

Hope it helps.

like image 24
Perdita Avatar answered Nov 14 '22 23:11

Perdita