您可以为您的复选框创建一个自定义委托,如下所示:
#include <QItemDelegate>
#include <QCheckBox>
#include <QPainter>
class CheckBoxDelegate: public QItemDelegate
{
Q_OBJECT
public:
CheckBoxDelegate(QObject *parent = 0);
void paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
QWidget *createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
void setEditorData( QWidget *editor,
const QModelIndex &index ) const;
void setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const;
void updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
mutable QCheckBox * theCheckBox;
private slots:
void setData(bool val);
};
CheckBoxDelegate::CheckBoxDelegate(QObject *parent ):QItemDelegate(parent)
{
}
void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
drawDisplay(painter,option,option.rect,index.model()->data( index, Qt::DisplayRole ).toBool()?QString(" ").append(tr("Yes")):QString(" ").append(tr("No")));
drawFocus(painter,option,option.rect);
}
QWidget *CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
theCheckBox = new QCheckBox( parent );
QObject::connect(theCheckBox,SIGNAL(toggled(bool)),this,SLOT(setData(bool)));
return theCheckBox;
}
void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
int val = index.model()->data( index, Qt::DisplayRole ).toInt();
(static_cast<QCheckBox*>( editor ))->setChecked(val);
}
void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
model->setData( index, (int)(static_cast<QCheckBox*>( editor )->isChecked() ) );
}
void CheckBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry( option.rect );
}
void CheckBoxDelegate::setData(bool val)
{
emit commitData(theCheckBox);
}
接下来在您的代码中将您的自定义项目委托分配给所需的列:
ui->myTable->setItemDelegateForColumn(5,new CheckBoxDelegate(ui->myTable));