how do i get a checkbox item from a QTableView and QStandardItemModel alone?

我们两清 提交于 2019-12-08 06:11:15

问题


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



来源:https://stackoverflow.com/questions/1850124/how-do-i-get-a-checkbox-item-from-a-qtableview-and-qstandarditemmodel-alone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!