Qt World Summit: Register Today!

acessing button created in a loop

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


                    QString str= QChar(s);
                    //QString myString = "a";
                    button[i][j] = new QPushButton(str);
                    controlsLayout->addWidget(button[i][j], i, j);
                    connect(button[i][j], SIGNAL(clicked()), this ,SLOT(buttonWasClicked()));

    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


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

  • Lifetime Qt Champion

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


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

    There is also
    "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