Qt中QTableView中加入Check列实现
通过Delegate创建QCheckBox来实现的Check列,只有在该列进入编辑模式时才能够Check/Uncheck。这显然不是我们想要的,网上翻来翻去,在一个国外论坛中看到了无需Delegate的实现方法,只需重写Model即可:
class MyModel : public QSqlQueryModel {
Q_OBJECT
public:
MyModel(QObject *parent = 0);
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
........
};
Qt::ItemFlags MyModel::flags(const QModelIndex &index) const {
Qt::ItemFlags flags = QSqlQueryModel::flags(index);
if (index.column() == aColWithCheckbox)
flags |= Qt::ItemIsUserCheckable;
else
flags |= Qt::ItemIsEditable;
return flags;
}
QVariant MyModel::data(const QModelIndex &index, int role) const {
QVariant value = QSqlQueryModel::data(index, role);
if (role == Qt::CheckStateRole && index.column() == aColWithCheckbox)
return (QSqlQueryModel::data(index).toInt() != 0) ? Qt::Checked : Qt::Unchecked;
else
return value;
}
bool MyModel::setData( const QModelIndex & index, const QVariant & value, int role)
{
if(index.isValid() && role == Qt::CheckStateRole&&index.column()==0)
{
if(value.value<int>()==Qt::Checked)
{
m_config->setAutoRun(index.row(), true);
}
else
{
m_config->setAutoRun(index.row(), false);
}
emit dataChanged(index, index);
return true;
}
return false;
}