I'm trying to append items to a QList at runtime, but I'm running on a error message. Basically what I'm trying to do is to make a QList of QLists and add a few customClass objects to each of the inner lists. Here's my code:
widget.h:
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
public slots:
static QList<QList<customClass> > testlist(){
QList<QList<customClass> > mylist;
for(int w=0 ; w<5 ; w++){
mylist.append(QList<customClass>());
}
for(int z=0 ; z<mylist.size() ; z++){
for(int x=0 ; x<10 ; x++){
customClass co = customClass();
mylist.at(z).append(co);
}
}
return mylist;
}
};
customclass.h:
class customClass
{
public:
customClass(){
this->varInt = 1;
this->varQString = "hello world";
}
int varInt;
QString varQString;
};
main.cpp:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
QList<QList<customClass> > list;
list = w.testlist();
w.show();
return a.exec();
}
But when I try to compile the application, it gives off this error:
error: passing `const QList<customClass>' as `this' argument of `void List<T>::append(const T&) [with T = customClass]' discards qualifiers
I also tried inserting the objects using foreach:
foreach(QList<customClass> list, mylist){
for(int x=0 ; x<10 ; x++){
list.append(customClass());
}
}
The error was gone, but the customClass objects weren't appended, I could verify that by using a debugging loop in main that showed the inner QLists sizes as zero. What am I doing wrong?
Qt Reference says:
const T & at ( int i ) const
but not:
T& at ( int i )
so there's no non-const version of at
. You have to use operator[]
instead.
So change it to:
mylist[z].append(co);
and it will work. I even tested it.
I think the foreach version doesn't work, because in foreach(QList<customClass> list, mylist)
QList<customClass> list
is not reference. But foreach(QList<customClass>& list, mylist)
doesn't compile. So you'll have to use the normal for(...)
version.
The error must be reported on the following line:
for(int z=0 ; z<mylist.size() ; z++){
for(int x=0 ; x<10 ; x++){
customClass co = customClass();
mylist.at(z).append(co); // Error is here
}
}
QList::at(int);
returns a const reference to the object at index i.
You should use QList::operator[](int i);
that return a non const reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With