Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
dyesdyes Avatar asked Sep 19 '13 15:09

dyesdyes


1 Answers

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.

like image 191
Nemanja Boric Avatar answered Oct 13 '22 20:10

Nemanja Boric