How to access C++ enum from QML?

后端 未结 7 658
清歌不尽
清歌不尽 2020-12-04 18:03
class StyleClass : public QObject {
public:
    typedef enum
        {
            STYLE_RADIAL,
            STYLE_ENVELOPE,
            STYLE_FILLED
        }  Styl         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 18:40

    You can wrap the enum in a class which derives from QObject (and that you expose to QML):

    style.hpp :

    #ifndef STYLE_HPP
    #define STYLE_HPP
    
    #include 
    #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
        // Qt 4
        #include 
    #else
        // Qt 5
        #include 
    #endif
    
    // Required derivation from QObject
    class StyleClass : public QObject
    {
        Q_OBJECT
    
        public:
            // Default constructor, required for classes you expose to QML.
            StyleClass() : QObject() {}
    
            enum EnStyle
            {
                STYLE_RADIAL,
                STYLE_ENVELOPE,
                STYLE_FILLED
            };
            Q_ENUMS(EnStyle)
    
            // Do not forget to declare your class to the QML system.
            static void declareQML() {
                qmlRegisterType("MyQMLEnums", 13, 37, "Style");
            }
    };
    
    #endif    // STYLE_HPP
    

    main.cpp:

    #include 
    #include "style.hpp"
    
    int main (int argc, char ** argv) {
        QApplication a(argc, argv);
    
        //...
    
        StyleClass::declareQML();
    
        //...
    
        return a.exec();
    }
    

    QML Code:

    import MyQMLEnums 13.37
    import QtQuick 2.0    // Or 1.1 depending on your Qt version
    
    Item {
        id: myitem
    
        //...
    
        property int item_style: Style.STYLE_RADIAL
    
        //...
    }
    

提交回复
热议问题