Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Compile error when using Q_GADGET macro



  • Hi all,
    I opened a new Qt Quick Application, just to learn the behavior of Q_GADGET macro

    below is the code,

    main.cpp

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    #include "base.h"
    
    int main(int argc, char *argv[])
    {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    
        QGuiApplication app(argc, argv);
    
        qmlRegisterType<Base>("Base",1,0,"Base");  // register here
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
        return app.exec();
    }
    

    base.h

    #ifndef BASE_H
    #define BASE_H
    
    #include <QObject>
    
    class Base
    {
        Q_GADGET
    
    public:
        Base();
    
    };
    Q_DECLARE_METATYPE(Base)
    
    
    #endif // BASE_H
    

    base.cpp

    #include "base.h"
    
    
    Base::Base()
    {
    
    }
    

    When building my application i am getting the error,
    D:\Qt\5.15.2\msvc2019\include\QtQml\qqmlprivate.h:142: error: C3668: 'QQmlPrivate::QQmlElement<T>::~QQmlElement': method with override specifier 'override' did not override any base class methods
    with
    [
    T=Base
    ]

    Compiler used: MSVC 2019 32 bit

    Can someone please help me, what is the issue.

    Thanks in advance


  • Moderators

    @Vinoth-Rajendran4 said in Compile error when using Q_GADGET macro:

    qmlRegisterType<Base>("Base",1,0,"Base"); // register here

    Q_GADGETs cannot be registered as QML types.



  • @sierdzio : Thanks for the reply.

    In the documentation, it is mentioned Q_GADGET macro supports Q_PROPERTY, Q_ENUM. How do we expose them to QML ?


  • Moderators

    Yes, QML understands gadgets, can modify properties etc. But it cannot instantiate a gadget, so you cannot register it as type. It's a pretty annoying limitation... and not very well documented.

    So, to use a gadget in QML, make sure some object creates the gadget on C++ side, then returns it. Something like (pseudo code):

    class MyController : public QObject
    {
      Q_OBJECT
    
      Q_INVOKABLE MyGadget getGadget() const;
    };
    
    struct MyGadget
    {
      Q_GADGET
      Q_PROPERTY(QString title MEMBER title)
      QString title = "Hello world!";
    };
    
    // QML:
    console.log("Title is:", myController.getGadget().title)
    

    You can also use gadget in a property instead of Q_INVOKABLE.



  • @sierdzio , Thanks for your clear explanation with code snippet. I got the point.


Log in to reply