What is correct way to convert QGyroscopeReading to QVector3D?

192 Views Asked by At

Is there a correct/good way to convert QGyroscopeReading to QVector3D in Qt5?

QGyroscopeReading has its x,y and z values stored as qreal, while QVector3D uses float.

Since qreal is not guaranteed to be float (it's type is specified at Qt build time), the warning-free naive conversion looks really ugly:

QGyroscopeReading gr;
QVector3D myVec(static_cast<float>(gr.x())
  , static_cast<float>(gr.y())
  , static_cast<float>(gr.z()));

Surely there is something better?

2

There are 2 best solutions below

2
Scheff's Cat On BEST ANSWER

From Qt doc. QGyroscopeReading Class:

QGyroscopeReading Units

The reading contains 3 values, measured in degrees per second that define the movement of the device around the x, y and z axes. Unlike QRotationReading, the values represent the current angular velocity rather than a fixed rotation. The measurements are in degrees per second.

So, conversion of qreal to float is your least problem except you just want to store the values in a QVector3D (remembering that this doesn't represent a point or vector in 3D space). But if this is the case, then your conversion is fine. (Although, I don't understand why not to store gyroscope reading just as QGyroscopeReading.)

If you want to apply QGyroscodeReading to a QVector3D (e.g. to display the effect), then you could apply the rotations to a predefined vector (e.g. QVector3D(0, 0, 1)). For a cumulate update, the time would be necessary as well (to convert angular velocities to angles).

For the time, the QGyroscopeReading::timestamp() could be interesting (i.e. determine duration from current timestamp and the previous one). Though, the doc. is not very encouraging:

Note that some platforms do not deliver timestamps correctly. Applications should be prepared for occasional issues that cause timestamps to jump backwards.

0
Konstantin T. On

It's designed to look ugly. It has to remind you that there is some dangerous code here.

To prevent spreading such code in the project inherit your class from QVector3D and define constructor with qreal parameters.

class QRealVector3D: public QVector3D
{
QRealVector3D (qreal x, qreal y, qreal z):
QVector3D (static_cast<float>(x)
  , static_cast<float>(y)
  , static_cast<float>(z)
{}
}