我有一个模型
class TreeModel : public QAbstractItemModel
TreeItem
我用我的排除列==1的实例填充。在第 1 列中,我创建了CheckBoxes
:
QVariant TreeModel::data(const QModelIndex &index, int role) const {
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole) {
if (role == Qt::CheckStateRole) {
if (index.column() == 1) {
if (index.row() == 1) {
return Qt::Unchecked;
} else
return Qt::Checked;
}
}
return QVariant();
}
if (role == Qt::DisplayRole) {
if (index.column() != 1) {
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
return item->data(index.column());
}
}
return QVariant();
}
我可以将这些 CheckBoxes 雕像设置为Qt::Checked
orQt::Unchecked
但我的问题是:
稍后单击它们时我无法更改它们(但是setData
用适当的index.column==1
and调用role==Qt::CheckStateRole
)。我见过的例子ItemDelegate
- 只有这似乎有效。这是真的?在这种情况下我必须使用委托吗?
这是我的setData()
功能:
bool TreeModel::setData(const QModelIndex & index, const QVariant & value,
int role) {
if (role==Qt::CheckStateRole && index.column() == 1) {
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
QTreeWidgetItem *check = static_cast<QTreeWidgetItem*>(index.internalPointer());
//if (item->data(index.column()) == Qt::Checked)
if (value == Qt::Checked){
int i=1;
//check->setCheckState(1,Qt::Checked); //SIGSEGV
}else{
//(item->data(index.column())) = Qt::Unchecked;
int i=2;
//check->setCheckState(1,Qt::Unchecked);
}
emit dataChanged(index, index);
return true;
}
emit dataChanged(index, index);
return true;;
}
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const {
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEditable;
}