Qtableview中的用户可编辑复选框

use*_*455 7 qt qt4

我想实现一个用户可编辑的复选框,QTableView其中使用QAbstractModel创建.我可以分配已选中和未选中的复选框但无法使其可编辑.标志设置为QItemIsUserCheckable.

Spo*_*Fan 14

您可以通过实现这样的模型setData()方法轻松完成:

bool yourModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid())
        return false;
    if (role == Qt::CheckStateRole)
    {
        if ((Qt::CheckState)value.toInt() == Qt::Checked)
        {
            //user has checked item
            return true;
        }
        else
        {
            //user has unchecked item
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记你的模型的data()方法:

QVariant ProxyModelSubobjects::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (role == Qt::CheckStateRole && index.column() == COLUMN_WITH_CHECKBOX)
    {
        //return Qt::Checked or Qt::Unchecked here
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)


dte*_*ech 1

您想要实现的是自定义委托。查看QAbstractItemDelegate类以获取有关实际实现的更多信息。