在Qt中用C++动态添加未知数量的按钮到UI

dye*_*yes 4 c++ user-interface qt

我试图在网格布局中插入QPushButton非常简单,但我不会提前知道这个数字.

这是我有的:

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()
{

}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

所以我知道这不会起作用,因为在当前循环结束时将删除该对象.

我考虑在main中创建QPushButton的QList(例如)并将其传递给testapp类,但我不确定它是一个很好的解决方案.可能有更好的方法.

编辑:由于某些原因,它没有编译.现在是.我讨厌那个到来的时候.

Nem*_*ric 5

实际上,不,在循环结束时不会删除该对象,因为您要在堆上分配它,而不是在堆栈上分配:

 QPushButton* panelButton = new QPushButton();
Run Code Online (Sandbox Code Playgroud)

在这种情况下,按钮将在其parent(ui.PanelButtonGridLayout)被销毁时自动销毁.

如下面的注释所述,对象的父级将通过addWidget方法在内部设置.

文档:

注意:项目的所有权转移到布局,布局负责删除它.