In Qt I'm trying to set up my own QWidget so everything should work good due to memory management and other things. But I can't seem to get it all right with pointers, heap and stack. I have my widget MyWidget that have a QList with some objects. I can't figure out how to set up everything right.
You can see my code below and I have some questions regarding this:
The instace variable list is created on the heap, would it be better to create it on the stack?
In my list I have pointers, would it be better to just create the object on the stack and append it to the list? (So that I don't have pointers in the list at all)
When I append the objects to the list will they get the list as their parent automatically? So when I delete the list all objects inside the list will be deleted?
The for each loop I'm trying to use isn't working, I got "a pointer/array type was expected for this operation instead of 'int'"
In my code I want to create other widgets that takes the object from the list as parameters. Is it the right way to do it like I have? MyOtherWidget's instance method looks like this: MyOtherWidget(MyObject *myObject, QWidget *parent)
Thanks for your help! I'm new to Qt and C++ so it would be great if you could guide me in the right direction. How can I setup this in the right way to make it easy, don't get memory leaks and use as little memory as needed. How would you setup the same thing?
This is my code:
MyWidget.h:
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0);
~MyWidget();
private:
QList<MyObject*> *list;
};
MyWidget.cpp:
MyWidget::MyWidget(QWidget *parent)
{
ui.setupUi(this);
list = new QList<MyObject*>();
for (int i = 0; i<10; i++)
{
MyObject *myObject = new MyObject("Hello",this);
list->append(myObject);
}
foreach(MyObject *myObject, list)
{
//Lets say I want to create other widgets here and that they takes a MyObject as a parameter
MyOtherWidget *myOtherWidget = new MyOtherWidget(myObject,this);
}
}
MyWidget::~MyWidget(){
delete list;
}