我想将函数动态地发送到 SLOT - 这个想法是使用相同的按钮设置(使代码重用)但具有不同的处理程序:
函数调用:
buttonSetup(loginButton, "Login", 100, 200, 100, 25, &KHUB::handleLogin);
buttonSetup(registerButton, "Register", 225, 200, 100, 25, &KHUB::handleRegister);
函数设置:
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));
}
我试图将函数作为参数传递并根据指针获取其名称(这并不代表代码在此处的处理方式),但我不确定这是否是最佳解决方案甚至一个办法。有谁知道这是否可行以及我如何才能做到这一点?
按照@Slyps [工作代码] 的指示进行编辑:
函数调用:
buttonSetup(&loginButton, "Login", 100, 200, 100, 25, &KHUB::handleLogin);
buttonSetup(®isterButton, "Register", 225, 200, 100, 25, &KHUB::handleRegister);
函数设置:
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);
}
最佳答案
您需要使用更新的语法:
connect(button, &QPushButton::released, this, fptr);
关于c++ - 在 SLOT 中动态调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27547478/