Question

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);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top