how do i get a checkbox item from a QTableView and

2019-06-06 18:13发布

Seems using model.setData(index, Qt::Checked,Qt::CheckStateRole) is not enough to get the checkbox working right. Any suggestions?

1条回答
狗以群分
2楼-- · 2019-06-06 18:42

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

查看更多
登录 后发表回答