简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM