QTreeView Checkboxes

Drise picture Drise · Nov 17, 2011 · Viewed 19.7k times · Source

I know this has been asked a bunch of times, but I cant seem to find anything relevant.

Using the simpletreemodel tutorial that comes packaged with Qt, how would I add checkboxes?

Answer

JediLlama picture JediLlama · Nov 18, 2011

Firstly, you'll need to modify TreeItem to keep track of the checked state:

private:
    ...
    bool checked;

and a setter and getter:

bool isChecked() const { return checked; }
void setChecked( bool set ) { checked = set; }

Now the model will need to be modified so that the view knows about the check state:

QVariant TreeModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    TreeItem *item = static_cast<TreeItem*>(index.internalPointer());

    if ( role == Qt::CheckStateRole && index.column() == 0 )
        return static_cast< int >( item->isChecked() ? Qt::Checked : Qt::Unchecked );

    if (role != Qt::DisplayRole)
        return QVariant();

    return item->data(index.column());
}

and modify the model's flags method to let views know that the model contains checkable items:

Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;

    Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    if ( index.column() == 0 )
        flags |= Qt::ItemIsUserCheckable;

    return flags;
}

I think this should do it. If you want to be able to update the TreeItem check state when the user ticks and unpicks the items, then you'll need to provide the QAbstractItemModel::setData method in your TreeModel.