BPS C++ API  2.24.4
BpsVariant Class Reference

Hook up custom variable types and classes in QVariant. More...

#include <bpsvariant.h>

Static Public Member Functions

template<typename T >
static void registerCompare ()
 Register custom type/class for QVariant equal operator.
 
template<typename F , typename T >
static void registerConvertTo ()
 Register custom type for QVariant conversion to other types. More...
 

Detailed Description

Hook up custom variable types and classes in QVariant.

By hooking up, it is possible to use the compare operator of the class instead of just comparing the value of the data pointers. Also, direct conversion to other known QVariant types is possible.

Limitations given by current QVariant implementation:

  • Only same type can be compared.
  • Converting in the other direction not possible.

Example usage in a class:

class Complex
{
public:
Complex(double aReal = 0.0, double aImg = 0.0) : mReal(aReal), mImg(aImg)
{
int metaType = QMetaType::type("Complex");
if (!metaType || !QMetaType::isRegistered(metaType)) {
metaType = qRegisterMetaType<Complex>(); // register meta type
BpsVariant::registerCompare<Complex,Complex>(); // needs operator==Complex
BpsVariant::registerConvertTo<Complex,QString>(); // needs convertTo(QString...)
BpsVariant::registerConvertTo<Complex,double>(); // needs convertTo(double...)
} // if
} // constructor
QString toString() const
{
return bStr("{%1,%2}").arg(mReal).arg(mImg);
} // toString
operator QVariant() const
{
return QVariant::fromValue<Complex>(*this);
} // convert to QVariant
bool operator==(const Complex aOther)
{
return qFuzzyCompare(mReal, aOther.mReal) && qFuzzyCompare(mImg, aOther.mImg);
} // operator==
bool convertTo(QString* aValue, bool* aOk = nullptr) const
{
*aValue = toString();
if (aOk) *aOk = true;
return true;
} // convertTo QString
bool convertTo(double* aValue, bool* aOk = nullptr) const
{
*aValue = mReal;
if (aOk) *aOk = true;
return true;
} // convertTo double
private:
double mReal;
double mImg;
};
#define bStr(aStr)
Encapsulation for string literals.
Definition: bpsglobals.h:125
bool isRegistered() const const
int type(const char *typeName)

Usage example:

QVariant v1a(Complex(2.0, 3.0));
QVariant v1b(Complex(2.0, 3.0));
QVariant v2(Complex(4.0, 5.0));
qDebug() << "v1a == v1a:" << (v1a == v1a);
qDebug() << "v1a == v1b:" << (v1a == v1b);
qDebug() << "v1a == v2:" << (v1a == v2);
qDebug() << v1a.toDouble() << v1a.toString() << v2;

Member Function Documentation

◆ registerConvertTo()

template<typename F , typename T >
static void BpsVariant::registerConvertTo ( )
inlinestatic

Register custom type for QVariant conversion to other types.

In case a conversion to QString is provided, the QDebug stream output will also work (see output of variable v2 in the example).


The documentation for this class was generated from the following file: