Search code examples
c++buttonqwidgetqt6

C++ Qt add multiple widget like QPushButton with variable Names


I want to add some Widget (QPushButton for example) in my central Widget inside a layout

I can do it with :

QPushButton *but1 = new QPushButton(ui->centralwidget);
    but1->setText("button1");
    ui->audiolayout->addWidget(but1);

Now my problem is that I don't know how many buttons I will have to create because it depends of the results of another function.

So what I want to do is each new button is named like

name = but + functionresult

int but_index;
for (but_index = 1; but_index < functionresult; but_index++)
{
QPushButton *butfunctionresult = new QPushButton(ui->centralwidget);
}

I can't find the correct way to do this


Solution

  • Widget's name isn't in QWidget, but in QObject.

    Use setObjectName(QString("but%1").arg(functionresult)), or something similar, to set a proper name for your button, setText(...) for the string displayed on the button itself, and store them in a vector (if you don't need to access individually to each button by name), or a map (if you need to access them by name).

    Example:

    // Use only ONE of these containers, no need to have the two.
    QVector<QPushButton*> anonymousStorage ;    // Access buttons through their index.
    QMap<QString,QPushButton*> namedStorage ;   // Access buttons through an internal name.
    
    for (auto but_index = 1 ; but_index < functionresult ; but_index++) {
        // Build the two required strings: internal name + display name.
        // "extfunc1" and "extfunc2" should return something suitable: string, integer, ... according to the current index.
        QString name = QString("button%1").arg(extfunc1(but_index)) ;
        QString display = QString("Button %1").arg(extfunc2(but_index)) ;
    
        // Create the button.
        auto newbut = new QPushButton(ui->centralwidget) ;
        newbut->setObjectName(name) ;
        newbut->setText(display) ;
        // Insert here any call to "connect" or other customization functions.
    
        // Store the new button inside ONE of these containers.
        anonymousStorage->push_back(newbut) ;
        namedStorage[name] = newbut ;
    }
    

    To retrieve / use them:

    // Click on button 12 - assuming you checked it exists before, obviously...
    anonymousStorage[12]->click() ;
    
    // Click on button "Commit" - assuming you checked it exists before, obviously...
    namedStorage["buttonCommit"]->click() ;