One of many possible solutions. Assuming that class Pile
is not a QObject
and you need to create plural instances of this class, we would nee so container to store those Pile
s. There are standard containers and there is Qt's own container template QList
, which is a mixture of list, vector and queue.
Ensure that you use QList in mainwindow.h header:
#include <QList>
In MainWindow
class declare member variable:
QList<Pile> piles;
In function that handles click signal:
void MainWindow::buttonClick() {
Pile p(size);
// do some stuff with p
piles.append(p); // or just piles.append(Pile(size));
// instead of creating separate copy Pile p(size);
}
That's all. Destructor of MainWindow
would destroy created objects and you can access them from other member functions.
What is the downside of this simplistic approach? QList
copies Pile
class into its dynamic storage by value. Your Pile class has to be properly copyable or at least trivial. QList
hides a lot of what it does to object and storage, the objects may be not stored continuously if they are big enough.
Story is slightly different if Pile is a Qt class.
QList's value type must be an assignable data type. This covers most
data types that are commonly used, but the compiler won't let you, for
example, store a QWidget as a value; instead, store a QWidget *.
You must use a pointer to a QObject
if you wish to use it with a QList
. The objects have to be allocated and deallocated properly, although Qt offers mechanics of automatic deallocation when parent object stops to exist.