本文介绍了我如何单独从 QTableView 和 QStandardItemModel 获取复选框项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎使用 model.setData(index, Qt::Checked,Qt::CheckStateRole) 不足以让复选框正常工作.有什么建议吗?

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

推荐答案

我相信你需要继承 QStandardItemModel;覆盖标志方法并返回 Qt::ItemIsUserCheckable 以及带有复选框的列的其他标志.下面是一个例子:

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

这篇关于我如何单独从 QTableView 和 QStandardItemModel 获取复选框项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 15:12