0

Within qt's item/view framework, I'm trying to save a QColorDialog as user data and then retrieve that dialog as the editor, as well as during paint, in a tableview.

In my class constructor I do

QStandardItem *item = new QStandardItem();
QColorDialog *colorDlg = new QColorDialog(QColor(0,0,255), this);
item->setData(QVariant::fromValue(colorDlg), ColorDialogRole);
mTableModel->setItem(0,2,item);

then, inside my delegate's paint function I have

void ReportFigureTableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QVariant vColorDlg= index.data(ReportFigure::ColorDialogRole);
    if(vColorDlg.isValid())
    {
        ////////////////////////////////////////////////
        // Program segfaults on the next line ... why?
        ////////////////////////////////////////////////
        QColorDialog *colorDlg = qvariant_cast<QColorDialog*>(vColorDlg);
        if(colorDlg != NULL)
        {
            painter->save();
            QStyleOptionViewItem opt = option;
            initStyleOption(&opt, index);

            painter->fillRect(opt.rect, colorDlg->selectedColor());
            painter->restore();
        }
        else
            QStyledItemDelegate::paint(painter, option, index);
    }
    else
        QStyledItemDelegate::paint(painter, option, index);
}

During runtime, the table shows up the first time (although with the wrong color ... different issue I assume). I double click to edit the cell and it brings up the dialog as expected. When I close, though, it segfaults on the indicated line. I don't understand why since I think I'm doing all the necessary checks.

ryan0270
  • 1,135
  • 11
  • 33

1 Answers1

0

You set the data on a QStandardItem object. Meanwhile you are retrieving the data on a QModelIndex object. Now why is the variant valid is a mystery. Maybe because ReportFigure::ColorDialogRole is equal to a build-in Qt role while it should be at least Qt::UserRole.

Anyway In the paint() method you can access the previously set item using

QStandardItem *item = mTableModel->itemFromIndex(index);
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • According to the documentation, QModelIndex::data() accesses the data of the referenced item; i.e. it's equivalent to itemFromIndex(index)->data(). ReportFigure::ColorDialogRole is already set to Qt::UserRole so should not be the problem. – ryan0270 May 07 '14 at 12:56