[英]Appending to QList of QList
我正在尝试在运行时将项目追加到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大小为零。 我究竟做错了什么?
Qt参考说:
常量T&at(int i)常量
但不是:
T&at(int i)
因此,没有at
非常量版本。 您必须使用operator[]
代替。
因此将其更改为:
mylist[z].append(co);
它会工作。 我什至测试了它。
我认为foreach版本不起作用,因为在foreach(QList<customClass> list, mylist)
QList<customClass> list
中未引用。 但是foreach(QList<customClass>& list, mylist)
无法编译。 因此,您必须使用普通的for(...)
版本。
该错误必须在以下行中报告:
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的对象的const引用。
您应该使用QList::operator[](int i);
返回非const引用。
foreach(T i,container)创建一个副本,如果您对其进行修改,则会修改该副本,而不是原始副本。 因此,应该始终使用foreach(const T&i,container)代替。
或者可以使用另一种从const成员函数获取值的方法,而不是在调用const函数之后调用函数,而直接使用属性值来访问值。 对于该属性,需要公开访问。
例如。
class ABC
{
public:
int a;
}
list.at(i).a; 而不是list.at(i).getValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.