Dynamically calling function inside SLOT

183 Views Asked by At

I would like to send functions dinamically to SLOT - The idea is to have the same button setup (make code reuse) but with different handlers:

Function call:

    buttonSetup(loginButton, "Login", 100, 200, 100, 25, &KHUB::handleLogin);
    buttonSetup(registerButton, "Register", 225, 200, 100, 25, &KHUB::handleRegister);

Function setup:

    void KHUB::buttonSetup(QPushButton *button, const QString name, int posX, int posY, int width, int height, void(KHUB::*fptr)())
{
    button = new QPushButton(name, this);
    button->setGeometry(QRect(QPoint(posX, posY), QSize(width, height)));

    //Event Listener
    connect(button, SIGNAL(released()), this, SLOT(fptr));
}

I was trying to pass the function as a parameter and acquire its name based on the pointer (which doesn't represent exactly how the code is disposed here), but I'm not sure if this is the best solution or even a solution. Does anyone know if that is possible to do and how am I able to do this?

Edited as pointed by @Slyps [Working Code]:

Function call:

    buttonSetup(&loginButton, "Login", 100, 200, 100, 25, &KHUB::handleLogin);
    buttonSetup(&registerButton, "Register", 225, 200, 100, 25, &KHUB::handleRegister);

Function setup:

    void KHUB::buttonSetup(QPushButton **button, const QString name, int posX, int posY, int width, int height, void(KHUB::*fptr)())
{
    *button = new QPushButton(name, this);
    (*button)->setGeometry(QRect(QPoint(posX, posY), QSize(width, height)));

    //Event Listener
    connect(*button, &QPushButton::released, this, fptr);
}
2

There are 2 best solutions below

0
On BEST ANSWER

You need to use the newer syntax:

connect(button, &QPushButton::released, this, fptr);
0
On

Either use the newer syntax like in ratchetfreaks answer, or, for the traditional syntax:

buttonSetup(loginButton, "Login", 100, 200, 100, 25, SLOT(handleLogin));
buttonSetup(registerButton, "Register", 225, 200, 100, 25, SLOT(handleRegister));

void KHUB::buttonSetup(QPushButton *button, const QString name, int posX, int posY, int width, int height, const char * slot)
{
    button = new QPushButton(name, this);
    button->setGeometry(QRect(QPoint(posX, posY), QSize(width, height)));

    //Event Listener
    connect(button, SIGNAL(released()), this, slot);
}

SLOT is just a preprocessor macro that turns its argument into a string and adds a flag wether its SLOT or SIGNAL ( and debug information in debug mode ). So if you write

connect(button, SIGNAL(released()), this, SLOT(fptr));

it doesnt pass the content of the variable fptr, but merely turns it into text "1fptr", and that slot obviously doesnt exist.