Unsolved QML call to ContextObject function with Enum Parameter
-
Hi everyone !
I have problem with this simple situation.
I use setContextObject to implement M-V-VM pattern.
And in QML, I want to call to VM function with enum parameter
but I getError: Unknown method parameter type: AdsProvider::EnumAdsProvider
This is my ViewModel Class
class MainWindowViewModel : public DynamicObject { Q_OBJECT public: MainWindowViewModel(QObject *parent = 0); Q_INVOKABLE void showLoginDialog(AdsProvider::EnumAdsProvider engine); };
This is the Enum declaration
class AdsProvider : public QObject { Q_OBJECT public: //static const QString GOOGLE; //static const QString BING; static QString Username; enum EnumAdsProvider { GOOGLE, BING, FACEBOOK }; Q_ENUMS(EnumAdsProvider) static void registerType() { qmlRegisterType<AdsProvider>("SystemConstants", 1, 0, "AdsProvider"); } };
I'm already register the custom Type & Enum like this
AdsProvider::registerType(); qmlRegisterType<DynamicObject>("core.dynamicobject", 1, 0, "DynamicObject"); qmlRegisterType<MainWindowViewModel>("Presentation.ViewModel", 1, 0, "MainWindowViewModel");
Here is the QML code call to VM function
import Presentation.ViewModel 1.0 import SystemConstants 1.0 ApplicationWindow { id:root ... ToolButton{ iconSource: "qrc:/login.png" onClicked: { showLoginDialog(AdsProvider.FACEBOOK); } } ... }
If I change the the parameter type in VM's function to int, it worked !!!
But I want to know exactly Enum type instead of int for any Enum parameters.Please Help !!! Thanks a lots !!!
-
@Dong
I usually put Q_ENUMS macro right afte Q_OBJECT. Maybe that helps? -
I know this in an old topic, but I'm having the exact same issue, and can't find a solution. Anyone know how to fix that properly ?
-
@EmilieG said in QML call to ContextObject function with Enum Parameter:
Anyone know how to fix that properly ?
as @t3685 already write, you have to ensure the enumeration is registered with
Q_ENUM()
orQ_ENUMS()
==> take a look at https://doc.qt.io/qt-5/qtqml-cppintegration-data.html#enumeration-types for more details
-
@EmilieG hi
this one way to do itclass MyClass: public QObject { Q_OBJECT public : enum class CurrentState : qint32{ STAND_BY, RUNNING, ERROR }; Q_ENUM(CurrentState) Q_INVOKABLE void testEnumArg(CurrentState s){ qDebug() << s; } }; Q_DECLARE_METATYPE(MyClass::CurrentState)
//in main.cpp for example qmlRegisterType<MyClass>("com.MyClass.test", 1, 0, "MyClass"); // make enum accessible in qml // + create an instance of that class and use setContextProperty() to make it avalable in qml and call the invokable method
// in qml import com.MyClass.test 1.0 ... classObject.testEnumArg(MyClass.STAND_BY)