自定义QVariant麻烦
Custom QVariant troubles
我正在使用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
。
相关文章:
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 查找奇数平方和时遇到麻烦
- 将双倍转换为 LPARAM 的麻烦
- 麻烦得到提升::记录器编译
- 翻转 ppm 图像C++麻烦
- 如何创建类似于 QVariant 的变体类
- 将 nullptr QVariant 与空 QString 进行比较,在 Qt5.9 和 Qt5.12 中给出了不同的输
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 搬家turtlebot_gazebo麻烦
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- 我的期末考试遇到了麻烦.代码不断循环回到我的订购菜单,不会显示我的总价
- 作为一个C++新手,我遇到了麻烦
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 从 json 字符串将 QVariant 转换为 QList<MyClass>
- 找麻木的麻烦
- 如何返回 QVariant 类型数组
- MySQL 从注入过渡到参数化时遇到麻烦
- 如何将 QVariant 转换为 QDomNode
- 字符串和双精度的麻烦,等值后再得到一个数字
- 自定义QVariant麻烦