Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch QTableWidgetItem check state change

Tags:

c++

qt

qt4

I have one QTableWidget with some QTableWidgetsItems on it. Some items use checkboxes. I've added the checkboxes using the follow code:

QTableWidgetsItem->setCheckState(Qt::Checked);

I would like now to call some function when this checkbox state change. Using a signal for example.

What may be the easiest way to accomplish this?

like image 399
RandomGuy Avatar asked Mar 17 '13 02:03

RandomGuy


1 Answers

The easiest way to do this is to capture signal(s) of QTableWidget with slot(s) in the class that contains QTableWidget. While it would seem that QTableWidget::itemActivated might be our best bet, it is uncertain whether or not this is emitted when the Qt::CheckState is equal to Qt::Checked. In addition, even if this was true, the signal would not provide you the capabilities of handling item unchecking which your application may need to do.

So, here is my proposed solution. Capture the QTableWidget::itemPressed and QTableWidget::itemClicked signals with slots defined in the class that contains the QTableWidget. As itemPressed should be called BEFORE the mouse button is released, and itemClicked should be called AFTER the mouse button is released, the Qt::CheckState for that QTableWidgetItem should only be set in between these two signal emissions. Thus, you can determine exactly when a QTableWidgetItem's checkState has changed with low memory overhead.

Here is an example of what these slots could look like:

void tableItemPressed(QTableWidgetItem * item)
{
    // member variable used to keep track of the check state for a 
    // table widget item currently being pressed
    m_pressedItemState = item->checkState();
}

void tableItemClicked(QTableWidgetItem * item)
{
    // if check box has been clicked
    if (m_pressedItemState != item->checkState())
    {
        // perform check logic here
    }
}

And the signals/ slots would be connected as follows:

connect(m_tableWidget,SIGNAL(itemPressed(QTableWidgetItem *)),this,SLOT(tableItemPressed(QTableWidgetItem *)));
connect(m_tableWidget,SIGNAL(itemClicked(QTableWidgetItem *)),this,SLOT(tableItemClicked(QTableWidgetItem *)));

Where m_tableWidget is the QTableWidget * you associate with your table widget.

like image 110
Sir Digby Chicken Caesar Avatar answered Sep 28 '22 08:09

Sir Digby Chicken Caesar