QVariant is not working for user defined datatype

  • Hello There,

    I am facing difficulty with QVariant class. I've defined a sub class of QDateTime and trying to assign it to QVariant and read back. Q_DECLARE_METATYPE(myClass) and qRegisterMetaType declarations are in place still QVariant is not getting initialized with my defined class. Please suggest what is wrong here.

    #include <QCoreApplication>
    #include <QDateTime>
    #include <QVariant>
    #include <qdebug.h>
    class myClass:public QDateTime
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        myClass mc;
        mc.setDate (QDateTime::currentDateTime().date ());
        mc.setTime (QDateTime::currentDateTime() .time ());
        qDebug() << mc.date().day () << mc.date().month()  << mc.date().year () ;
        QVariant vc;
       vc.setValue (mc);
        myClass dateTime = vc.value<myClass>();
        qDebug() << dateTime.date().day () << dateTime.date().month()  << dateTime.date().year () ;
        return a.exec();

  • @narinder83 said in QVariant is not working for user defined datatype:

    myClass dateTime = vc.value<myClass>();

    it might just be a problem of the default copy constructor. try defining it.

    class myClass : public QDateTime
    myClass() = default;
    ~myClass() = default;
    myClass(myClass&& other)
    myClass(const myClass& other)
    :QDateTime(static_cast<const QDateTime&>(other))
    myClass& operator=(const myClass& other){
    QDateTime::operator=(static_cast<const QDateTime&>(other));
    return *this;
    myClass& operator=(myClass&& other){
    return *this;

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.