Search code examples
c++qtqvariant

Store QList<Custom> in QVariant


I have a class defined as this:

cdataentry.h:

#ifndef CDATAENTRY_H
#define CDATAENTRY_H

#include <QObject>
#include <QString>
#include <QVariant>
#include <QtOpcUa>
#include <QMetaType>

#include <cnodetype.h>
#include <cdatastatus.h>

/**
 * @brief   A class providing data and methods to describe a single OPCUA ua
 *          node in the user input table.
 */
class CDataEntry : public QObject
{
    Q_OBJECT

public:

    CDataEntry(const QString& np, QObject* parent = nullptr);
    ~CDataEntry();

    QString nodePath() const;

private:

    /**
     * @brief   Obsolute path to the node on the MDE server
     */
    const QString m_nodePath;

};

Q_DECLARE_METATYPE(CDataEntry); // to be able to store it in QVariant.

#endif // CDATAENTRY_H

I am trying to store a QList<CDataEntry> object in a QVariant. For that end, I have provided the Q_DECLARE_METATYPE(CDataEntry);. The problem is that the code doesn't compile, what I get is:

error: no matching function for call to 'QVariant::QVariant(QList<CDataEntry>&)'

What am I missing here?


Solution

  • You need to add default constructor, copy constructor and copy/assignment operator to your QObject subclass.

    Like this:

    CDataEntry& operator=(const CDataEntry&){}
    CDataEntry(QObject* parent = nullptr):QObject(parent){}
    CDataEntry(const CDataEntry&){}
    //...
    CDataEntry(const QString& np, QObject* parent = nullptr)
    

    after that you can use it in QVariant like that:

        CDataEntry test;
        QList<CDataEntry> list;    
        list.append(test);
    
        QVariant var = QVariant::fromValue<QList<CDataEntry>>( list );
        auto t = var.value<QList<CDataEntry>>();
        qDebug() << t.first().nodePath();