【问题标题】:Dynamically calling function inside SLOTSLOT 内动态调用函数
【发布时间】: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(&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, &QPushButton::released, this, fptr);
}

【问题讨论】:

  • 在一个边节点上:你的参数 button 到底是什么目的?您没有将新创建的 QPushButton 的地址放入您调用 buttonSetup 的范围的变量 loginButton/registerButton 中。为此,您需要使用**。如果你不想在那个范围内使用loginButton/registerButton,那么这个参数就没用了。
  • 你是对的,这导致应用程序崩溃

标签: c++ qt function parameter-passing slot


【解决方案1】:

您需要使用较新的语法:

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

【讨论】:

    【解决方案2】:

    要么使用像 ratchetfreaks 答案中的新语法,要么使用传统语法:

    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 只是一个预处理器宏,它将其参数转换为字符串,并添加一个标志 SLOTSIGNAL (以及调试模式下的调试信息)。所以如果你写

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

    它没有传递变量fptr的内容,只是把它变成了文本“1fptr”,而那个槽显然不存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2012-04-12
      • 2017-03-10
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多