c++qtqt5qtableviewqvector3d

How to display QVector3D in one cell in QTableView via qAbstractTableModel's subclass


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?


Solution

  • 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