PDA

View Full Version : custom delegate for QSqlRelationalModel



mak_user
19th June 2011, 19:36
This is what I have implemented in my custom delegate:


class pcheckboxdelegate : public QStyledItemDelegate
{
Q_OBJECT

public:
pcheckboxdelegate(QObject *parent = 0) : QStyledItemDelegate(parent) {}

QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QCheckBox *editor = new QCheckBox(parent);
return editor;
}

void setEditorData(QWidget *editor, const QModelIndex &index) const
{
bool value = index.model()->data(index, Qt::DisplayRole).toBool();
QCheckBox *checkBox = static_cast<QCheckBox*>(editor);
if (value == true ) {
checkBox->setCheckState(Qt::Checked);
} else {
checkBox->setCheckState(Qt::Unchecked);
}
}

void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QCheckBox *checkBox = static_cast<QCheckBox*>(editor);
if(checkBox->checkState() == Qt::Checked) {
model->setData(index, true);
} else {
model->setData(index, true);
}
}

void updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
};


I am trying to achieve that I get checkbox in the cell for boolean type in database instead of true or false text that I am getting.
With this code I can only see checkbox after doubleclick on the cell. Even then "true" text stays in the cell.
Could you help me implement delegate that would always show checkbox and I will not have to doubleclick the cell to use it?

joyer83
20th June 2011, 08:48
If check box is all you need, then you can use the default delegate. It can render checkboxes if you set Qt::CheckStateRole role to one of the values of Qt::CheckState.

mak_user
21st June 2011, 22:12
How to do that? Should I reimplement data and setData function in subclassed QSqlRelationalModel?