Qt: Get click event from button inside QTableWidget cell



QTableWidget is a very flexible control allowing to manage various type of widgets inside each cell. However some widgets like button require an immediate action in consequence of click event. Insert a button inside a table cell is very easy but we need a way to get the click event since there will be a button for each new row in the table.


To be more precise we need a way to know which button of all the table rows has been clicked. Solution to this problem can be various but the use of QSignalMapper object can be the best way. Basically we need to define a slot function to call in consequence of button click event with an integer param that, in our example, will return the row number containing the button just clicked.

QSignalMapper ButtonSignalMapper;

private slots:
    void CellButtonClicked(int RowNum);

Now the second step is to make the connection between the button object just inserted into the cell and the slot function receiving the click event with param:

QPushButton* pButton = new QPushButton("Click Me", MyTable);
MyTable->setCellWidget(RowNum, ColNum, pButton);

connect(pButton, SIGNAL(clicked()), &ButtonSignalMapper, SLOT(map()));
ButtonSignalMapper.setMapping(pButton, RowNum);
connect(&ButtonSignalMapper, SIGNAL(mapped(int)), this, SLOT(CellButtonClicked(int)));

Using this code for each row added to the table control will allow to get click event and know the button's row generating it. Obviously, instead of row number you can use any ID number you need.




3 Comments:

Good contents but why with black ad.

Anonymous
August 10, 2015 at 4:48 AM comment-delete

What happen if I delete some rows? Then the mapping is incorrect.

Anonymous
August 31, 2016 at 5:14 PM comment-delete

This is only an example for show the way to get it. As written at the end of aricle, instead of row number you can use any ID number you need based to your software logic.

August 31, 2016 at 11:37 PM comment-delete

Post a Comment