0

在 qt 的项目/视图框架中,我试图将 QColorDialog 保存为用户数据,然后将该对话框作为编辑器以及在绘制期间在 tableview 中检索。

在我的类构造函数中,我做

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

然后,在我的代表的绘画功能中,我有

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

在运行时,表格第一次显示(虽然颜色错误......我假设不同的问题)。我双击编辑单元格,它会按预期弹出对话框。但是,当我关闭时,它会在指示的行上出现段错误。我不明白为什么,因为我认为我正在做所有必要的检查。

4

1 回答 1

0

您在QStandardItem对象上设置数据。同时,您正在检索QModelIndex对象上的数据。现在为什么变体有效是一个谜。也许是因为ReportFigure::ColorDialogRole它等于一个内置的 Qt 角色,而它至少应该是 Qt::UserRole

无论如何在该paint()方法中,您可以使用访问先前设置的项目

QStandardItem *item = mTableModel->itemFromIndex(index);
于 2014-05-07T08:48:20.037 回答