2014-05-06 68 views
0

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

在我的类的构造函数我做

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

然后,我委托的paint函数中我有

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

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

回答

0

您将数据设置为QStandardItem对象。同时,您正在检索QModelIndex对象上的数据。现在为什么变种有效是一个谜。也许是因为ReportFigure::ColorDialogRole等于内置Qt角色while it should be at least Qt::UserRole

无论如何在paint()方法可以访问使用

QStandardItem *item = mTableModel->itemFromIndex(index); 
+0

先前设置的项目根据该文件,QModelIndex ::数据()访问所引用的项目的数据;即它相当于itemFromIndex(index) - > data()。 ReportFigure :: ColorDialogRole已经设置为Qt :: UserRole,所以不应该是问题。 – ryan0270