I modified the example of the Qt website: EditableTreeModel Example so that in the tree view I get CheckBoxes next to each Item.
But ... How can I make them dependent on each other? That is, if the parent's ChechBox is selected automatically, check all of their children. And if one of those children later becomes Uncheck, the father becomes partially checkered.
Here the functions that I have modified to make the CheckBoxes come out.
In TreeModel
function data
:
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()){
return QVariant();
}
TreeItem *item1 = static_cast<TreeItem*>(index.internalPointer());
if ( role == Qt::CheckStateRole && index.column() == 0 )
{
return static_cast< int >( item1->isChecked() ? Qt::Checked : Qt::Unchecked );
}
if (role != Qt::DisplayRole && role != Qt::EditRole)
return QVariant();
TreeItem *item = getItem(index);
return item->data(index.column());
}
In TreeModel
function flags
:
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEditable | QAbstractItemModel::flags(index)|Qt::ItemIsUserCheckable;
}
In TreeModel
function setData
:
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
TreeItem *item = getItem(index);
if(role == Qt::CheckStateRole)
{
qDebug()<<"Ischecked"<<item->isChecked();
if(item->isChecked())
item->setChecked(false);
else
item->setChecked(true);
emit dataChanged(index, index);
return true;
}
if (role != Qt::EditRole)
return false;
bool result = item->setData(index.column(), value);
if (result)
emit dataChanged(index, index);
return result;
}
In TreeItem
I added the function setChecked
again:
void TreeItem::setChecked(bool set)
{
checked=set;
}
In TreeItem
I added the function isChecked
again:
bool TreeItem::isChecked()
{
return checked;
}
Being checked
a variable type bool
within my class TreeItem
.