Important: Please read the Qt Code of Conduct -

Disable tristate of checkbox in QTableView

  • I'm displaying a checkbox in a QTableView by overriding the table view model's flags-function:

    Qt::ItemFlags TableViewModel::flags(const QModelIndex& in_index) const
        if (CHECKBOX_COL_INDEX == in_index.column())
            return QStandardItemModel::flags(in_index) | Qt::ItemIsUserCheckable | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
        return QStandardItemModel::flags(in_index);

    This works, but the resulting checkbox has three states. I want it to have only two.
    I found the flags Qt::ItemIsTristate (deprecated) and Qt::ItemIsAutoTristate, but I can't work out how to use them.
    Any help?

  • @qwasder85
    Assuming, from what you say (I don't know if it's true, I'm slightly surprised that it does...) that QStandardItemModel::flags(in_index) is returning Qt::ItemIsAutoTristate among its flags, then to switch off, and switch others on, all in one line you would need:

     return (QStandardItemModel::flags(in_index) & ~Qt::ItemIsAutoTristate) | Qt::ItemIsUserCheckable | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    Adding a flag is always done via |, removing a flag via & ~.

  • @JonB
    You were right about being surprised. Because it wasn't returning Qt::ItemIsAutoTristate.
    I'm overriding the setData()-function in that model as well and apparently the issue came from handling the checked-state in there. I'm not yet sure how this resulted in this behavior.

    So thank you, the issue was NOT with the flags.

Log in to reply