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

  1. Good contents but why with black ad.

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

    ReplyDelete
  3. 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.

    ReplyDelete
  4. I am adding btn_save to tableWidget want to handle click event of it

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

    My handler
    void CellButtonClicked(int RowNum)
    {
    ShowMsg("Hit" + QString::number(RowNum) );
    }

    but handler does not execute

    ReplyDelete

Post a Comment

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