PDA

View Full Version : Managing dynamically created buttons



Akame.L
9th April 2017, 18:06
Hello,
I created some labels and buttons dynamically. I want to know how can I handle each button when it's clicked.
I know in a normal way for one button it goes like this:


void test::on_btnName_clicked()
{
// Some code here ....
}

So what abt this case ?
I have no idea so here's what I've done so far
test.cpp


#include "test.h"
#include "ui_test.h"

test::test(QWidget *parent) : QMainWindow(parent), ui(new Ui::test)
{
ui->setupUi(this);
for (int i = 1; i <= 4; i++){

for (int j = 1; j <= 4; j++){
QString btnName = "Button "+QString::number(i)+","+QString::number(j);
QString lblName = "Label "+QString::number(i)+","+QString::number(j);
QPushButton* panelButton = new QPushButton(btnName);
QLabel* label = new QLabel(lblName);
panelButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->PanelButtonGridLayout->addWidget(panelButton,i,4);
if(j<4) {
ui->PanelButtonGridLayout->addWidget(label,i,j);
}
}
}
}

test::~test()
{
delete ui;
}

weiweiqiao
9th April 2017, 19:54
After you create button, you could create connections between button's clikced and slot which you want to do.

Lesiok
10th April 2017, 09:52
Read about QObject::connect, QObject::sender and QSignalMapper.