[Qt-interest] QTableWidgetItem with Validator (only numbers) and Range

Matthias Pospiech matthias.pospiech at gmx.de
Sun May 3 17:01:48 CEST 2009


I have now implemented a DoubleSpinBoxDelegate, which I have copied from 
the Qt "Spin Box Delegate Example".

I am adding the Delegate via

    DoubleSpinBoxDelegate * delegateSpinBox = new 
DoubleSpinBoxDelegate(this) ;
    tableViewPowerDegree->setItemDelegateForColumn(1,delegateSpinBox);

however when I start to edit (double click) the value is always reset to 
0, although the value was in a valid range.

The Code for the DoubleSpinBoxDelegate is the following:

DoubleSpinBoxDelegate::DoubleSpinBoxDelegate( QObject* parent /*= 0*/ ) 
: QItemDelegate(parent)
{
}


DoubleSpinBoxDelegate::~DoubleSpinBoxDelegate()
{
}


QWidget *DoubleSpinBoxDelegate::createEditor(QWidget *parent,
                                             const QStyleOptionViewItem 
&/* option */,
                                             const QModelIndex &/* index 
*/) const
{
    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);
    editor->setMinimum(0);
    editor->setMaximum(100);

    return editor;
}

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

    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();
    int 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);
}



More information about the Qt-interest-old mailing list