【发布时间】:2014-12-18 13:15:44
【问题描述】:
我想动态地向 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);
}
【问题讨论】:
-
在一个边节点上:你的参数
button到底是什么目的?您没有将新创建的 QPushButton 的地址放入您调用buttonSetup的范围的变量loginButton/registerButton中。为此,您需要使用**。如果你不想在那个范围内使用loginButton/registerButton,那么这个参数就没用了。 -
你是对的,这导致应用程序崩溃
标签: c++ qt function parameter-passing slot