Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to receive notification of checking checkbox in QAbstractItemModel?



  • I have a TreeModel derived from QAbstractItemModel in which I have several TreeItem's which have check boxes by using this function.

    Qt::ItemFlags MyTreeModel::flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return 0;
    
        Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
    
        if (index.column() == 0 && !index.parent().isValid()) {
            flags |= Qt::ItemIsUserCheckable;
    
            return flags;
        }
    
        return QAbstractItemModel::flags(index);
    }
    

    I'd like to receive some sort of callback or notification if the item is checked but not sure how this is done. I suspect there is already some way to do this that I'm not aware of.

    Any ideas?



  • @johnby
    There isn't a specific signal (your "callback or notification") when the checked value is changed in the model; there might be in any attached view, I don't know.

    But if you override your model's setData() method you should see that it is called with parameter role == Qt::CheckStateRole for this case, which you can act on.

    I think https://stackoverflow.com/questions/17786086/how-set-qcheckbox-in-qabstractitemmodel illustrates this approach.

    Alternatively, I have not tested this, but signal dataChanged() (https://doc.qt.io/qt-5/qabstractitemmodel.html#dataChanged) may also be emitted for this, with role == Qt::CheckStateRole, to which you could attach a slot.

    Does this answer your question?



  • @johnby
    There isn't a specific signal (your "callback or notification") when the checked value is changed in the model; there might be in any attached view, I don't know.

    But if you override your model's setData() method you should see that it is called with parameter role == Qt::CheckStateRole for this case, which you can act on.

    I think https://stackoverflow.com/questions/17786086/how-set-qcheckbox-in-qabstractitemmodel illustrates this approach.

    Alternatively, I have not tested this, but signal dataChanged() (https://doc.qt.io/qt-5/qabstractitemmodel.html#dataChanged) may also be emitted for this, with role == Qt::CheckStateRole, to which you could attach a slot.

    Does this answer your question?



  • Close enough, yes, thanks.


Log in to reply