Important: Please read the Qt Code of Conduct -

QPushButton and Connect with variables

  • I have the following problem:

    I want to create an unknown amount of QPushButtons and connect the clicked event to a function which needs a variable. It looks like this:

            buttons[i] = new QPushButton(filename);
            buttons[i]->connect(buttons[i], SIGNAL(clicked(bool)), this, SLOT(readbutton(i)));

    Without the "i" in the readbutton function it would work like this. But I need to know which button was clicked in the function "readbutton". Can I use the connect function or is there another easy way to call the function with the integer variable "i".
    I'm new to QT and a programming beginner so it would be great if you could it explain it in an easy understandable way.

    Thanks a lot.

  • Lifetime Qt Champion

    It works with the new signal & slot syntax and a small lambda

    connect(buttons[i], &QPusbButton::clicked, this, [this, i]() { readButton(i); });

  • Thank you very much!

Log in to reply