acessing button created in a loop



  • in my program i am creating many buttons in a loop as shown below

    for(i=0;i<7;i++)

    {
    
        for(j=0;j<7;j++)
    
        {
    
            if(count<=26)
    
            {
    
                    QString str= QChar(s);
    
                    //QString myString = "a";
    
                    button[i][j] = new QPushButton(str);
    
                    s=s+1;
    
                    button[i][j]->setText(str);
    
                    controlsLayout->addWidget(button[i][j], i, j);
    
                    connect(button[i][j], SIGNAL(clicked()), this ,SLOT(buttonWasClicked()));
    
                count++;
    
            }
    
        }
    
    }
    

    i now need to aces these buttons using signal and slots..now what can i do is write a common program for all buttons. but i need to write separate code for each button click of the buttons above..can anyone guide me properly how to access each of the buttons clicked event separately


  • Lifetime Qt Champion

    Hi,

    What do you mean by "separated code" ? What will be the differences ?


  • Qt Champions 2016

    Hi
    You cannot assign different names for the slot function (when using loop) ,
    unless you resort to some ugly macros.

    To have different slots for the clicked(), you would have to connect to each
    using another slot name.

    However, in buttonWasClicked() you can use sender()

    like

    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if( button != NULL ) {
    button point to the button that emitted the clicked()
    }
    

    There is also
    http://doc.qt.io/qt-5/signalsandslots.html#advanced-signals-and-slots-usage
    "The QSignalMapper class is provided for situations where many signals are connected to the same slot and the slot needs to handle each signal differently."

    which sounds like what you want?



  • @SGaist i mean for each button click i want to print each character. basically i am trying to write a keyboard program..



  • @mrjj thanks a lot


  • Lifetime Qt Champion

    The QSignalMapper is the way to go and it will be simpler.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.