I'm trying to take a QVariant (in this case from a QProperty generated on a class) and based on the type, return a QWidget that allows for it to be edited appropriately.

a signature for the conversion function might look like this:

template<typename T>
QWidget * createWidget(const QString& label, const T& value, QWidget * parent = nullptr);

However, since I'm dealing with QVariants, Ill need some way to switch on the type of the QVariant in order to choose the correct function overload/template.

My idea was to simply have a giant switch statement, and specialize a template for each type (in order to avoid improper overload substitution, particularly with int-like types)


QWidget *createDisplayWidget(const QString &label, const QVariant &q_variant,
                            QWidget *parent = nullptr) {
    QWidget *display_widget = nullptr;
    switch (q_variant.userType()) {
        case QMetaType::Bool:
            display_widget = createWidget(label, q_variant.value<bool>(), parent);
        case QMetaType::Int:
            display_widget = createWidget(label, q_variant.value<int>(), parent);
    return display_widget;

I was wondering are there legitimate alternatives to this approach with different trade-offs? I can't think of any other method to accomplish this task, or something that better fits my use-case. It seems to me to be clear and only the new function and an additional case on the switch will have to be updated with new types, but that is also restrictive as it will require recompiling that portion of code.

  • Can you get (or hold on to) an instance of QMetaProperty rather than just the QVariant data?
    – Caleth
    Commented Jul 6, 2018 at 16:18
  • @Caleth maybe, but I need to query the properties on the class, aren't I limited to using QVariant anyway because of that?
    – Krupip
    Commented Jul 6, 2018 at 16:53


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.