tags:

views:

581

answers:

4

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

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

the error i'm getting during the Qlist append

error: invalid conversion from 'const MyInt*' to 'MyInt*' error:
initializing argument 1 of 'void QList::append(const T&) [with T = MyInt*]'

If anyone can point out what i'm doing wrong, that would be awesome.

A: 

The compiler is telling you all you need to now - you're trying to store a const T* as a T* and implicit conversions from const T* to T* are not allowed.
Just leave out the const when append()ing.

Georg Fritzsche
it worked, thanks so much!
colorfulgrayscale
A: 

I would say you should just be passing a regular MyInt* into QList::append. The "const T&" refers to the pointer type--QList is promising not to reassign the pointers you provide.

ChrisV
+2  A: 

You would need to use:

   QList<const MyInt*> myintarray;
PiedPiper
Was going to say that you wouldn't want to save const pointers because you'd leak (due to delete not working on them). But I looked it up, and to my surprise you can indeed delete a const pointer. Not sure if I like it, but...one learns something new every day I guess!
Hostile Fork
Okay, if I did that, then will that object be mutable? I want to loop through that list and edit some values, but that wouldn't be possible because that will discard the 'const' qualifier. Suggestions?
colorfulgrayscale
+5  A: 

So you created a list of:

QList<MyInt*> myintarray;

Then you later try to append

myintarray.append(new const MyInt(1,"intvar1",&parent));

The problem is new const MyInt is creating a const MyInt *, which you can't assign to a MyInt * because it loses the constness.

You either need to change your QList to hold const MyInts like so :

QList<const MyInt*> myintarray;

or you need to not create a const MyInt * by changing your appends to:

myintarray.append(new MyInt(1,"intvar1",&parent));

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

tamulj
makes even more sense...thanks
colorfulgrayscale