1

I'd like to display QVector3D in tableView, preferably like this: (x,y,z). I had subclassed the QAbstractTableModel class and implemented QAbstractTableModelSublass::data function:

QVariant data(const QModelIndex &index, int role= Qt::DisplayRole) const override
{
  ...
  if(role == Qt::DisplayRole)
  {  /* decide in which column and row to display the data*/
    QVector3D p(1.,2.,3.); return QVariant(p); 
  }
}

However, the target cell where the QVector3D should be displayed is empty. I'm quite positive that the correct QVariant instance is constructed, since I was able to print the value like this:

QVariant v = QVariant(p);
qDebug()<<v.value<QVector3D>();

What am I missing? How am I supposed to display the QVector3D in table in one cell?

dodol
  • 1,073
  • 2
  • 16
  • 33

2 Answers2

3

I would do it in the following way:

QVariant data(const QModelIndex &index, int role= Qt::DisplayRole) const
{
  ...
  if(role == Qt::DisplayRole)
  {  /* decide in which column and row to display the data*/
    QVector3D p(1.,2.,3.);
    return QString("(%1, %2, %3)").arg(p.x()).arg(p.y()).arg(p.z()); 
  }
}
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • Ah, in that case, if the model is editable, I suppose that should provide a validator? – dodol May 29 '15 at 08:52
  • 2
    Yes, you should validated the input string in the form of "(x, y, z)" or other, parse it and construct new QVector3D. – vahancho May 29 '15 at 10:07
2

The Qt::DisplayRole requires a QString in the variant, but you are providing a QVector3D. There is no conversion from QVector3D to QString in QVariant (see documentation).

You should either convert the Vector to a string representation yourself, or use a QStyledItemDelegate to override the displayText method for converting QVector3D to a string representations.

NB: Your debug output works, because there is a dedicated QDebug operator<<(QDebug dbg, const QVector3D &vector) for printing QVector3D in QDebug

king_nak
  • 11,313
  • 33
  • 58
  • QStyledItemDelegate::displayText is not even called (called qDebug in fn body) when QVector3D is (0,0,0). Meaning, nothing is displayed. Everything is fine when at least one component is not zero. If I don't use delegate and return QString in data() fn as described below in vahancho's answer, the value is displayed as expected. What kind of sorcery is this? – dodol May 29 '15 at 10:59