【问题标题】:Store QList<Custom> in QVariant将 QList<Custom> 存储在 QVariant 中
【发布时间】:2019-06-19 20:17:49
【问题描述】:

我有一个这样定义的类:

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&lt;CDataEntry&gt; 对象存储在QVariant 中。为此,我提供了Q_DECLARE_METATYPE(CDataEntry); 问题是代码无法编译,我得到的是:

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

我在这里错过了什么?

【问题讨论】:

  • 只有QList&lt;QVariant&gt;&amp; 的重载,因此您需要先将QList&lt;CDataEntry&gt; 转换为QList&lt;QVariant
  • 提供的两种解决方案都使错误消失,但随后我得到更多错误:C:\Qt\5.12.3\mingw73_64\include/QtCore/qmetatype.h:804:20: error: use of deleted function 'CDataEntry::CDataEntry(const CDataEntry&amp;)' return new (where) T(*static_cast&lt;const T*&gt;(t));我需要默认构造函数吗?
  • 所以我需要一个默认构造函数和一个拷贝构造函数。

标签: c++ qt qvariant


【解决方案1】:

您需要将默认构造函数、复制构造函数和复制/赋值运算符添加到您的 QObject 子类。

像这样:

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

【讨论】:

  • 你能提供operator=的正文吗?
  • @Bremen,它是空的 {} 但在你的情况下它可能看起来像这样: CDataEntry& operator=(const CDataEntry& old) { this->m_nodePath = old.nodePath();返回*这个;但是在这种情况下,m_nodePath 在类定义中不能是 const。
  • 是的,这是个问题。需要考虑清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多