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.



Comments

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model