qtcastingqvariant

QVariant use the type to static cast another variable


I create a structure with some variables to be able to use it and compare its value with range, or use on a data model with my QML GUI:

struct DataStruct
{
    DataStruct(QString name = "", QVariant value = QVariant(), QVariant minValue = QVariant(), QVariant maxValue = QVariant(), QString unit = "") :
        name(name), value(value), minValue(minValue), maxValue(maxValue), unit(unit) {}
    QString name;           /**< Name of the parameter */
    QVariant value;         /**< Value of the parameter */
    QVariant minValue;      /**< Minimum correct value for the paramter */
    QVariant maxValue;      /**< Maximum correct value for the parameter */
    QString unit;           /**< Unit (if exists) */
};

The objective is to add in a map some instances of this structure but with a specific name :

QMap<QString, DataStruct> m_params;  /**< Map with all parameters */

For this, I am using a class method which take QVariant(s) as inputs to initialize each instance of the structure :

void addParamToMap(QString name, QVariant value, QVariant minValue, QVariant maxValue, QString unit)
{
    m_params[name] = { name, value, minValue, maxValue, unit };
}

And I call this method with each parameter I want to add:

addParamToMap("MyParam", uint32_t(50), uint32_t(std::numeric_limits<uint32_t>::min()), uint32_t(std::numeric_limits<uint32_t>::max()));

What I wish is avoid copy/paste errors when I will have to add my parameters (because I have nearly 300 of them) when I copy/paste the type (here uint32_t) with my method for each inputs. For this, I want to do something like add this type as a new input of my class method with the QVariant::Type for example (here QMetaType::UInt) and use it to cast each value I give to my method in the correct type on my structure. For example:

void addParamToMap(QString name, QVariant::Type type, QVariant value, QVariant minValue, QVariant maxValue, QString unit)
{
    m_params[name] = { name, static_cast<type>(value),  static_cast<type>(minValue),  static_cast<type>(maxValue), unit };
}

And so call my method such as:

addParamToMap("MyParam", QMetaType::UInt, 50, std::numeric_limits<uint32_t>::min(), std::numeric_limits<uint32_t>::max());

But, because this type is an enum, I don't know how I can use it to cast correctly the values. Thank you in advance for any help or advice.


Solution

  • I am dummy, I didn't see the convert method from the QVariant class. Thank you @perivesta.