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

Pass enum into QML and use it in JavaScript. How?



  • Hello!
    I need to get enum from C++ into QML:

    class SomeClass : public QObject {
    
    	Q_OBJECT
    
    	public:
    
    		enum Types {
    			Type0 = 0,
    			Type1 = 1,
    			Type2 = 2
    		}; Q_ENUM(Types)
    };
    

    How to get it into QML and use it JavaScript?



  • @bogong

    class SomeClass : public QObject {
    
    	Q_OBJECT
            Q_PROPERTY(Types  type READ type WRITE setType NOTIFY typeChanged) //<
    
    	public:
    
    		enum class Types  : int{  //<
    			Type0 = 0,
    			Type1 = 1,
    			Type2 = 2
    		}; Q_ENUM(Types)
    
       Types  type()const{
            return m_type;
        }
        void setType(const Types &t){
            if(m_type!=s){
                m_type=t;
                emit typeChanged(m_type);
            }
        }
    signal : 
    void typeChanged(Types t);
    
     private :
       Types m_type  = Type0; //<
    
    }; 
    Q_DECLARE_METATYPE(SomeClass::Types ) //<
    

    //main.cpp

       SomeClass obj; // create class obj
       QQmlApplicationEngine engine;
       engine.rootContext()->setContextProperty("myObj",&obj); // make it known in QML
    
    
       qmlRegisterType<SomeClass>("com.my.comp", 1, 0, "SomeClass"); // register the enum
       
    

    //qml js

    import com.my.comp 1.0
    
    ..
    Image{
     source : myObj.type === SomeClass.Type0 ? "/typeZeroImg/img.png" : "autherImg/img.png"
    }
    


  • @LeLev said in Pass enum into QML and use it in JavaScript. How?:

    Q_DECLARE_METATYPE(SomeClass::Types )

    This forgotten for me. Thx. Issue closed.
    And it's not working if it inside of Singletone class because of disabled default constructor.


  • Moderators

    @bogong don't forget to set the topic to solved, when it's solved 😉


Log in to reply