Compile error when using Q_GADGET macro
-
Hi all,
I opened a new Qt Quick Application, just to learn the behavior of Q_GADGET macrobelow 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
-
@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.
-
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.