如何访问动态创建的按钮单击事件 Qt C++

How To Access Dynamically Created Buttons Click events Qt C++

我为数据库中的数据动态创建了按钮

QPushButton *btnComment = new QPushButton("Comment");
               btnComment->setProperty("id",qry.value(0).toString());

是我动态创建的按钮 我设置了一个连接

connect(btnComment, &QPushButton::clicked, this, &Planner::commentButton);

并在插槽上创建了一个函数

public slots:
    
    void commentButton();

如何获取 id 值以便在单击按钮后执行 SQL 查询

我测试了功能

void Planner::commentButton()
{
    
    QMessageBox inpass;
       inpass.setText("Comment");
       inpass.exec();
    return;
}

它有效,但在单击“确定”后应用程序关闭

我在控制台中得到类似的东西

QMainWindowLayout::addItem: Please use the public QMainWindow API instead

任何可能的方法?

更新

我能够通过将传递变量声明为全局变量来解决 lambda 问题

connect(btnComment,  &QPushButton::clicked, this, [this]{ commentButton(taskID); });

如评论中所述,您可以 connect 到 lambda 而不是直接到非静态成员。

Planner::commentButton 的 signature/definition 更改为...

void Planner::commentButton (QPushButton *button)
{
    
    /*
     * Use button accordingly.
     */
}

然后只需将您的 connect 调用更改为...

connect(btnComment, &QPushButton::clicked, this,
        [this, btnComment]
        {
            commentButton(btnComment);
        });

现在指向触发调用的 QPushButton 的指针将传递给 Planner::commentButton