自定义QVariant麻烦



我正在使用QVariant发现自定义类型,并尝试在我的项目中实现它。 问题是,当我认为它会使用复制构造函数时,它似乎使用默认构造函数创建了一个对象......

也许有什么我不明白的...

这是我的自定义类:

参数.h

#ifndef PARAMETER_H
#define PARAMETER_H
#include <QDebug>
#include <QMetaType>
#include "variable.h"
#include <QAbstractTableModel>
class Parameter : public Variable, public QAbstractTableModel
{
public:
Parameter();
Parameter(QString name, int min, int max, int val, QObject *parent);
Parameter(const Parameter &source);
private:
int m_value;
};
Q_DECLARE_METATYPE(Parameter)
#endif // PARAMETER_H

参数.cpp

包括"参数.h">

Parameter::Parameter() : Variable()
{
qDebug()<<"Default constructor";
m_value = 0;
setName("Test");
}
Parameter::Parameter(QString name, int min, int max, int val, QObject     *parent)
: Variable(name, min, max), QAbstractTableModel(parent)
{
qDebug()<<"constructor";
m_value = val;
}
Parameter::Parameter(const Parameter &source)
: Variable(source.getName(), source.getMin(), source.getMax()),
QAbstractTableModel(),
m_value(source.m_value)
{
qDebug()<<"copy constructor";  
}

我在类 MainWindow 中创建了一个参数实例。以下代码是此类构造函数的摘录:

Parameter *param = new Parameter("Param",0,100,10, this);
QVariant v = QVariant::fromValue(param);
Parameter op = v.value<Parameter>();
qDebug()<< op.getName();

此代码的输出为:

constructor
Default constructor 
Default constructor
"Test"

我想了解为什么默认构造函数被调用两次。以及我应该做什么,以便它调用复制构造函数(为了获得我创建的对象,其名称为"Param"(

非常感谢您的回答:)

指针存储在QVariant而不是值中。但想要检索价值。

如果无法转换该值,则将返回默认构造的值。

所以v.value<Parameter>();返回一个默认构造的对象,因为Parameter*无法转换为Parameter

最新更新