Hello everyone,
I did a search in the forum but didn’t find anything. (If I’m wrong, just link me the threads please).
I have some customs classes, and I need to map them with some QVariant.
What I’m doing is a constructor from a QVariant to instantiate them from the QVariant, and an operator QVariant() const in order to use static_cast to cast the object to a QVariant.
But now I’m facing one problem with QList. I have for example a QVariant containing a QList of QMap<QString, QVariant>. A QMap<QString, QVariant> represent my object A. I’m able to cast a QMap to a A and vice versa.
My question is from a QVariant like this (QList<QMap<QString, QVariant> >), how can I cast it to a QList of my custom type (QList<A>).
Code:
#include <QDebug>
using namespace std;
class A
{
public:
int value;
public:
A () {cout << "Default constructor" << endl;}
A (int arg)
{
this->value = arg;
}
A (QVariant variant) throw (int)
{
cout << "Constructor from variant" << endl;
if (!variant.canConvert(QVariant::Map))
throw 1;
QMap<QString,QVariant> mapVariant = variant.toMap();
this->value = mapVariant["value"].toInt();
}
A operator=(A& copy)
{
cout << "Constructor by copy" << endl;
this->value = copy.value;
return (*this);
}
virtual ~A ()
{}
operator QVariant() const
{
QMap<QString,QVariant> mapAns = QMap<QString,QVariant>();
mapAns.insert("value", this->value);
return mapAns;
}
};
Q_DECLARE_METATYPE(A);
Q_DECLARE_METATYPE(QList<A>);
int main(int argc, const char *argv[])
{
cout << "[Log] Beginning of the prog(" << argv[0] << ")" << endl;
QList<QMap<QString, QVariant> > listVariant = QList<QMap<QString, QVariant> >();
QMap<QString, QVariant> mapA1 = QMap<QString,QVariant>();
QMap<QString, QVariant> mapA2 = QMap<QString,QVariant>();
QMap<QString, QVariant> mapA3 = QMap<QString,QVariant>();
QMap<QString, QVariant> mapA4 = QMap<QString,QVariant>();
mapA1.insert("value", 4);
mapA2.insert("value", 9);
mapA3.insert("value", 3);
mapA4.insert("value", 2);
listVariant.append(mapA1);
listVariant.append(mapA2);
listVariant.append(mapA3);
listVariant.append(mapA4);
QList<A> listA = static_cast<QList< A > >(listVariant);
qDebug() << "[Debug] listA (" << listA << ")";
cout << "[Log] End of the prog" << endl;
return 0;
}
↧