Seems using model.setData(index, Qt::Checked,Qt::CheckStateRole) is not enough to get the checkbox working right. Any suggestions?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I believe you would need to subclass QStandardItemModel; override flags method and return Qt::ItemIsUserCheckable along with other flags for the column with check boxes. Below is an example:
class TableModel : public QStandardItemModel
{
public:
TableModel();
virtual Qt::ItemFlags flags ( const QModelIndex & index ) const;
};
TableModel::TableModel()
{
//???
}
Qt::ItemFlags TableModel::flags ( const QModelIndex & index ) const
{
Qt::ItemFlags result = QStandardItemModel::flags(index);
if (index.column()==1) result |= Qt::ItemIsUserCheckable;
return result;
}
here's how I was initializing controls:
QStandardItemModel* tableModel = new TableModel();
// add columns
tableModel->insertColumn(0, QModelIndex());
tableModel->insertColumn(1, QModelIndex());
// add rows
tableModel->insertRows(0, 1, QModelIndex());
tableModel->insertRows(1, 1, QModelIndex());
// set text item
QModelIndex index0 = tableModel->index(0, 0, QModelIndex());
tableModel->setData(index0, QVariant("test item"), Qt::EditRole);
// set checkbox item
QModelIndex index1 = tableModel->index(0, 1, QModelIndex());
tableModel->setData(index1, QVariant(Qt::Checked), Qt::CheckStateRole);
ui->tableView->setModel(tableModel);
hope this helps, regards