QList class member and item operations
Hi all.
i have a non-really-qt related newbie problem that you surely can solve easily.
i have a class 'Model' which holds some members. one of thos is a QList.
this is the code for that class:
Header:
Code:
#ifndef MODEL_H
#define MODEL_H
#include <QList>
class Model
{
public:
Model();
QList<QString> list() const;
private:
QList<QString> m_list;
};
#endif // MODEL_H
cpp
Code:
#include "model.h"
#include <QString>
Model::Model()
{
}
QList<QString> Model::list() const
{
return m_list;
}
when i execute this snippet of code:
Code:
Model m;
qDebug() << "Before clear()";
for(int i=0;i<m.list().count();i++)
{
qDebug() << m.list().at(i);
}
m.list().clear();
qDebug() << "After clear()";
for(int i=0;i<m.list().count();i++)
{
qDebug() << m.list().at(i);
}
i get this output:
Code:
"Before clear()"
"item1"
"item2"
"After clear()"
"item1"
"item2"
i think that the problem is the fact that calling m.list() returns me a copy of the QList instead of a reference to it.
i think that one way to solve this is returning a pointer to the QList instead, but i'm wondering if there is another way to do this avoiding pointers.
sorry for the long post and thanks if you read since here :)
Re: QList class member and item operations
Quote:
i think that the problem is the fact that calling m.list() returns me a copy of the QList instead of a reference to it.
Yes it returns a copy as per the implementation you have done !
What do you want reference for ? May be if you tell what you want to do more, we can suggest some better way.
Re: QList class member and item operations
the needs i have on that member are:
insert a new item in the list;
get all items;
delete all items;
by now, i have those 3 functions exposed in 3 public methods in my model:
insertItem(QString item); //note that the type is not QString normally
items();
clearItems();
i think this is a fat interface, because the method items().clear() exists but "doesn't work" and clearItems() shouldn't be there.
hope my needs are clear