dyesdyes
dyesdyes

Reputation: 1217

Dynamically add an unknown number of button to UI in Qt in C++

I'm trying to inset QPushButton in a grid layout which is pretty easy but I won't know the number in advance.

Here is what I have:

testapp.cpp

#include "testapp.h"

testApp::testApp(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            QPushButton* panelButton = new QPushButton();
            panelButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
            ui.PanelButtonGridLayout->addWidget(panelButton,i,j);
        }
    }
}

testApp::~testApp()
{

}

main.cpp

#include <QtGui/QApplication>

#include "testapp.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    testApp w;
    w.show();
    return app.exec();
}

So I know that this won't work because the object is going to be deleted at the end of the current loop.

I thought about creating a QList (for example) of QPushButton in the main and pass it to the testapp class but I'm not sure it's a good solution. there might be way better ways.

EDIT: For some reasons, it wasn't compiling. It now is. I hate when that arrives.

Upvotes: 5

Views: 5614

Answers (1)

Nemanja Boric
Nemanja Boric

Reputation: 22157

Actually, no, the object will not be deleted at the end of the loop, as you're allocating it on the heap, and not on the stack:

 QPushButton* panelButton = new QPushButton();

In this case, buttons will be destroyed automatically when their parent (ui.PanelButtonGridLayout) is destroyed.

As the comments below state, the parent of the object will be set internally by addWidget method.

From the documentation:

Note: The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.

Upvotes: 6

Related Questions