简体   繁体   English

自定义QVariant麻烦

[英]Custom QVariant troubles

I am discovering Custom Types with QVariant and tried to implement it in my project. 我正在使用QVariant发现自定义类型,并尝试在我的项目中实现它。 The problem is, it seems like it creates an object with the default constructor when I thought it would use the copy constructor... 问题是,当我认为它将使用复制构造函数时,似乎使用默认构造函数创建了一个对象...

Maybe there is something I don't understand... 也许有些我不懂的东西

Here is my custom class : 这是我的自定义类:

Parameter.h Parameter.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

Parameter.cpp Parameter.cpp

include "parameter.h" 包括“ parameter.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";  
}

I create an instance of Parameter in a class MainWindow. 我在MainWindow类中创建Parameter的实例。 The following code is an extract of the constructor of this class : 以下代码摘录了该类的构造函数:

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

The output of this code is : 此代码的输出是:

constructor
Default constructor 
Default constructor
"Test"

I would like to understand why the default constructor is called twice. 我想了解为什么默认构造函数被调用两次。 And what I should do so that it calls the copy constructor instead (in order to get the object I created, whose name is "Param) 我应该做的是改为调用副本构造函数(以获取我创建的名称为“ Param”的对象)

Thank you a lot for your answers :) 非常感谢您的回答:)

You store pointer in your QVariant instead of value. 您将指针存储在QVariant而不是值中。 But want to retrieve value. 但是想找回价值。

If the value cannot be converted, a default-constructed value will be returned. 如果无法转换该值,则将返回默认构造的值。

so v.value<Parameter>(); 所以v.value<Parameter>(); returns a default-constructed object as Parameter* cannot be converted to Parameter . 返回默认构造的对象,因为Parameter*无法转换为Parameter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM