问题描述
我对QT很新。我一直在搞乱它一个星期。我在尝试向Qlist中添加自定义数据类型时遇到错误。
I'm pretty new to QT. I've been messing with it for a week now. I came across a error while I was trying to add a custom datatype to a Qlist like so
QObject parent;
QList<MyInt*> myintarray;
myintarray.append(new const MyInt(1,"intvar1",&parent));
myintarray.append(new const MyInt(2,"intvar2",&parent));
myintarray.append(new const MyInt(3,"intvar3",&parent));
,我的MyInt类是一个简单的int包装,看起来像这样
and my MyInt class is a simple wrapper for int and looks something like this
#ifndef MYINT_H
#define MYINT_H
#include <QString>
#include <QObject>
class MyInt : public QObject
{
Q_OBJECT
public:
MyInt(const QString name=0, QObject *parent = 0);
MyInt(const int &value,const QString name=0, QObject *parent = 0);
MyInt(const MyInt &value,const QString name=0,QObject *parent = 0);
int getInt() const;
public slots:
void setInt(const int &value);
void setInt(const MyInt &value);
signals:
void valueChanged(const int newValue);
private:
int intStore;
};
#endif
我在Qlist追加的错误
the error i'm getting during the Qlist append
如果任何人可以指出我做错了什么,这将是真棒。
If anyone can point out what i'm doing wrong, that would be awesome.
推荐答案
:
QList< MyInt *> myintarray;
然后您稍后尝试附加
myintarray.append(new const MyInt(1,"intvar1",&parent));
问题是新的const MyInt正在创建一个const MyInt *,你不能分配给
The problem is new const MyInt is creating a const MyInt *, which you can't assign to a MyInt * because it loses the constness.
您需要更改QList以容纳const MyInts,如下所示:
You either need to change your QList to hold const MyInts like so :
QList< const MyInt *> myintarray;
或者您不需要通过将附加内容更改为以下内容来创建const MyInt *:
or you need to not create a const MyInt * by changing your appends to:
myintarray.append(new MyInt(1,"intvar1",&parent));
您将选择的方法将取决于您想要如何使用QList。你只想要const MyInt *,如果你永远不想改变MyInt
The method you will choose will depend on exactly how you want to use your QList. You only want const MyInt * if you never want to change the data in your MyInt
这篇关于(C ++ QT)QList只允许追加常量类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!