#include <QSqlTableModel>#include <QVariant>#include <QBrush>class myModel : public QSqlTableModel{ Q_OBJECTpublic: explicit myModel(QObject *parent = 0); QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const; bool setData( const QModelIndex & index, const QVariant & value, int role); Qt::ItemFlags flags(const QModelIndex &index);};
#include "mymodel.h"#include <QSqlRecord>#include <QSqlTableModel>#include <QDebug>myModel::myModel(QObject *parent) : QSqlTableModel(parent){}QVariant myModel::data(const QModelIndex &index, int role) const{ QVariant value; if (index.column()==6) switch(role){ case Qt::CheckStateRole: if (record(index.row()).value(index.column()).toInt()==0) value = Qt::Unchecked; else value = Qt::Checked; break; case Qt::DisplayRole: value = QVariant(""); break; } if (!value.isValid()) value = QSqlTableModel::data(index,role); return value;}bool myModel::setData( const QModelIndex & index, const QVariant & value, int role){ if (index.isValid() && index.column() && role==Qt::CheckStateRole){ QSqlRecord rec = record(index.row()); bool chk = (value.toInt()==Qt::Checked); rec.setValue(index.column(),chk); return setRecord(index.row(),rec); } else return QSqlTableModel::setData(index,value,role);}Qt::ItemFlags myModel::flags(const QModelIndex &index){ if(index.column()==6) return Qt::ItemIsUserCheckable | QSqlTableModel::flags(index); return QSqlTableModel::flags(index);}
C++ (Qt)QVariant DisenchantPreviewModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole*/) const{ switch (role) { case Qt::CheckStateRole: if (index.column() == CheckboxColumn) return _uncheckedIndexesSet.contains(index.row()) ? Qt::Unchecked : Qt::Checked; break; default: break; } return QVariant();} bool DisenchantPreviewModel::setData(const QModelIndex &index, const QVariant &value, int role /*= Qt::EditRole*/){ if (role == Qt::CheckStateRole) { if (value.toBool()) _uncheckedIndexesSet.remove(index.row()); else _uncheckedIndexesSet += index.row(); emit dataChanged(index, index); return true; } return false;}