0

I'm trying to add a spinbox item delegate to a specific column in my table. After looking though the example in Qt I copied most of that code and implemented it but when I call setItemDelegateForColumn() my application crashes. The column index is valid. Any ideas what I've done wrong?

Main Calling Method:

BinarySpinboxDelegate binarySpinboxDelegate;
ui->UsersTable->setItemDelegateForColumn(users->at(0).size()-1 ,&binarySpinboxDelegate);

Custom Spinbox Implementation:

#include "binaryspinboxdelegate.h"
#include <QSpinBox>

BinarySpinboxDelegate::BinarySpinboxDelegate(QObject *parent) : QStyledItemDelegate(parent)
{

}

QWidget* BinarySpinboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const
{
    QSpinBox* editor = new QSpinBox(parent);
    editor->setFrame(false);
    editor->setMinimum(0);
    editor->setMaximum(1);

    return editor;
}

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

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

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

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

void BinarySpinboxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const
{
    editor->setGeometry(option.rect);
}
Jarrod Cabalzar
  • 408
  • 1
  • 5
  • 24

1 Answers1

1

And I'm an idiot -_- It turns out I was silly enough to declare the delegate inside an initialisation function for the table, which then goes out of scope after the function finishes. Moved it to the header file so it exists for the life of the object and it was fine.

Jarrod Cabalzar
  • 408
  • 1
  • 5
  • 24
  • 1
    This is also not the first time I was bitten by Garbage Collector. But your answer still saved me. I am working with editing delegates in PySide. – foresightyj Jan 09 '14 at 03:27
  • Did you declare it header file? Is it pointer or normal variable? You can declare it as pointer and in init function you must create an object and assign its address to pointer. `BinarySpinboxDelegate *binarySpinboxDelegate;` and `binarySpinboxDelegate = new BinarySpinboxDelegate(ui->tableView);` <<-- if you use it for table. – Mubin Icyer Oct 03 '18 at 10:34