Converting QList to QVariant

21.2k views Asked by At

The class contains this:

Q_PROPERTY(QList<double> switch1 READ switch1 WRITE setSwitch1 NOTIFY switch1Changed)

void setSwitch2(QList<double> arg)
{
    if (m_switch2 != arg)
    {
        m_switch2 = arg;
        emit switch2Changed(arg);
    }
}

The below works:

setSwitch2(QList<double>::fromVector(QVector<double>::fromStdVector(data->switch2)));

but now my datatype is QVariantList instead of QList<double>.

How should I replace QList with QVariant now?

This doesn't work:

setSwitch1(QVariantList::fromVector(QVector<QVariant>::fromStdVector(data->switch1)));
4

There are 4 answers

4
László Papp On BEST ANSWER

Just use this constructor:

QVariant::QVariant(const QList & val)

Constructs a new variant with a list value, val.

I.e. when storing a QList as a QVariant, the template type of the QList has to be a type that is OK for QVariant. There is no other constructor or conversion method for this.

You should be writing this:

QVariant variant(
    QList<double>::fromVector(QVector<double>::fromStdVector(data->switch2))
);

setSwitchVariant(variant);
0
Serge On

I understand that it is not relevant for the author. But maybe someone will come in handy.

qRegisterMetaTypeStreamOperators<QList<double>>("Stuff");
QList<double> lst;
// convert
QVariant varLst = QVariant::fromValue(lst);
// back
lst = varLst.value<QList<double>>();
0
ZolotovPavel On

If no need constructor:

QList<QUrl> params;
QVariant varParams;
varParams.setValue<QList<QUrl>>( params );
0
Andreas Hagmüller On

There is the QVariant constructor for lists: QVariant(const QList &list) and the typedef QVariantList. Both togheter in a nice template:

template <class T> static QVariant toVariant(const QList<T> &list)
{
    QVariantList variantList;
    variantList.reserve(list.size());
    for (const auto& v : list)
    {
        variantList.append(v);
    }
    return variantList;
}