[Qt-interest] ItemDelegate with custom DoubleSpinBox

Matthias Pospiech matthias.pospiech at gmx.de
Tue May 19 15:06:18 CEST 2009


I am using the following code to generate a ItemDelegate with a 
DoubleSpinBox.

The problem I have is that the spinbox is displayed not inside the 
table, but somewhere in the Dialog and
that the app crashed at second creation of the editor.

I must however access the DoubleSpinBox, because I need to set its 
properties.

The usage is the following:
------------------
    DoubleSpinBoxDelegate * delegateSpinBox = new 
DoubleSpinBoxDelegate(this) ;
    delegateSpinBox->setEditor(new QDoubleSpinBox(this));
    delegateSpinBox->Editor()->setRange(0,20000);
    delegateSpinBox->Editor()->setDecimals(4);
    tableViewPowerDegree->setItemDelegateForColumn(1,delegateSpinBox);
   
The class is this (copied from SpinBox example with changes to the 
editor origin)
------------------  
DoubleSpinBoxDelegate::DoubleSpinBoxDelegate( QObject* parent /*= 0*/ )
: QItemDelegate(parent)
, editor(0)
{
    editor = new QDoubleSpinBox;
}


DoubleSpinBoxDelegate::~DoubleSpinBoxDelegate()
{
    delete editor;
}


void DoubleSpinBoxDelegate::setEditor(QDoubleSpinBox * doubleSpinBox)
{
    delete editor;
    editor = doubleSpinBox;
}

QDoubleSpinBox * DoubleSpinBoxDelegate::Editor()
{
    return editor;
}

QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent,
                                             const QStyleOptionViewItem 
&/* option */,
                                             const QModelIndex &/* index 
*/) const
{
    return editor;
}

void DoubleSpinBoxDelegate::setEditorData(QWidget *editor,
                                          const QModelIndex &index) const
{
    double value = index.model()->data(index, Qt::EditRole).toDouble();

    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->setValue(value);
}

void DoubleSpinBoxDelegate::setModelData(QWidget *editor, 
QAbstractItemModel *model,
                                         const QModelIndex &index) const
{
    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->interpretText();
    double value = spinBox->value();

    model->setData(index, value, Qt::EditRole);
}

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



Matthias



More information about the Qt-interest-old mailing list