[SOLVED] How To Access Dynamically Created Buttons Click events Qt C++

Issue

I Created buttons dynamically for data from the database

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

Is the button that i created dynamically
I set a connect

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

and created a function on slots

public slots:
    
    void commentButton();

How can I get the id value so I can execute a SQL query after the button click

I tested the function

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

It works but after clicking OK the application closes

I get something like this in the console

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

Any possible approach ?

Update

I was able to solve the lambda issue by declaring the passing variable as a global variable

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

Solution

As mentioned in the comment you can connect to a lambda rather than directly to a non-static member.

Change the signature/definition of Planner::commentButton to…

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

Then simply change your connect call to…

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

Now a pointer to the QPushButton that triggered the call will be passed to Planner::commentButton.

Answered By – G.M.

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *