我试图在运行时将项附加到QList,但运行时出现错误消息。基本上,我要做的是创建一个QLists的QList,并向每个内部列表添加一些customClass对象。下面是我的代码:
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();
}但是当我尝试编译应用程序时,它给出了这个错误:
error: passing `const QList<customClass>' as `this' argument of `void List<T>::append(const T&) [with T = customClass]' discards qualifiers我还尝试使用foreach插入对象:
foreach(QList<customClass> list, mylist){
for(int x=0 ; x<10 ; x++){
list.append(customClass());
}
}错误消失了,但是没有附加customClass对象,我可以通过在main中使用一个调试循环来验证这一点,该循环将内部QLists大小显示为零。我做错了什么?
发布于 2010-03-22 23:23:44
Qt Reference说:
常量T& at ( int I)常量
但不是:
T at (整数i)(&A)
所以没有非常数版本的at。您必须改用operator[]。
因此,将其更改为:
mylist[z].append(co);它会起作用的。我甚至测试过了。
我认为foreach版本不起作用,因为在foreach(QList<customClass> list, mylist)中,QList<customClass> list不是reference。但是foreach(QList<customClass>& list, mylist)不能编译。所以你必须使用普通的for(...)版本。
发布于 2010-03-22 23:27:54
必须在以下行报告错误:
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);返回对索引i处的对象的常量引用。
您应该使用返回非常数引用的QList::operator[](int i);。
发布于 2010-03-23 05:06:39
foreach( T i,container )创建一个副本,如果您修改它,则修改的是副本,而不是原始副本。因此,应该始终使用foreach( const T& i,container)。
https://stackoverflow.com/questions/2493297
复制相似问题