[SOLVED] QT push button to create object

Issue

I am trying to create a little game using a pile structure, and im using QT Widget Application, my problem is: i have a class Pile that needs to be initialized with Pile p1(size), and "size" is obtained when the button "Create" is pushed. The problem is: when i do this, my object p1 will be exclusive to the PushButton function, and consequently the other functions of my program cannot access p1 as it disappears as soon as the PushButton function ends, and i need to access p1 with other functions from my mainwindow.cpp.

How to solve this problem? Do i need to initialize p1 differently?

Solution

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 Piles. 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.

Answered By – Swift – Friday Pie

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *