将 QList<Custom> 存储在 QVariant 中

Store QList<Custom> in QVariant

我有一个 class 定义如下:

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

我正在尝试将 QList<CDataEntry> 对象存储在 QVariant 中。为此,我提供了 Q_DECLARE_METATYPE(CDataEntry); 问题是代码无法编译,我得到的是:

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

我在这里错过了什么?

您需要为您的 QObject 子类添加默认构造函数、复制构造函数和 copy/assignment 运算符。

像这样:

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

之后你可以像这样在 QVariant 中使用它:

    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();