Search code examples
c++qtqtablewidgetqt-signalsqtablewidgetitem

The QTableWiget::cellChanged signal is not emitted for cells with a QTableWidgetItem


I have the following code, creating a table with two cells:

QTableWidget table(2, 1);
QObject::connect(&table, &QTableWidget::cellChanged, [](int column, int row) {
    qDebug() << column << row;
});

auto item = new QTableWidgetItem();
item->setData(Qt::DisplayRole, 42);
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren);
table.setItem(1, 0, item);

I would expect the cellChanged signal to be emitted when any of the cells change, but this is not the case: it only works with the first cell, not with the second one.

Why isn't the cellChanged signal emitted for cells with a QTableWidgetItem?


Solution

  • Do not set the Qt::ItemNeverHasChildren flag. For some reasons, even if your item actually does not have children, it will mess with the associated signals. The following code works as expected:

    QTableWidget table(2, 1);
    QObject::connect(&table, &QTableWidget::cellChanged, [](int column, int row) {
        qDebug() << column << row;
    });
    
    auto item = new QTableWidgetItem();
    item->setData(Qt::DisplayRole, 42);
    item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled);
    table.setItem(1, 0, item);