Search code examples
qtqmlqtquick2qtabbar

Using c++ enum in qml


I have an enum that I use in qml

class SettingManager : public QObject
{
    Q_OBJECT
public:
    enum BookKinds{
         BookKind1=0,
         BookKind2=1,
     };
     Q_ENUMS(BookKinds)
     Q_PROPERTY(BookKinds bookKind READ bookKind WRITE setBookKind NOTIFY bookKindChanged)

     explicit SettingManager(QObject *parent = nullptr);
     void setBookKind(BookKinds dkob);
     BookKinds bookKind();
  signals:
    void bookKindChanged();
};

in main.cpp I registerd SettingManager

qmlRegisterType<SettingManager>("Test",1,0,"SettingManager");

I use this in qml file

  onCurrentIndexChanged:
    {
        if(tbarBookKindForDisplay.currentIndex==0)
        {
           settingManager.bookKind=BookManager.BookKind1;
        }
        else if(tbarBookKindForDisplay.currentIndex==1){
            settingManager.bookKind=BookManager.BookKind2;
         }           
    }

when CurrentIndex of TabBar changes below error occurs:

Error: Cannot assign [undefined] to int


Solution

  • You register the type as SettingManager but use it as BookManager. The correct code is:

    settingManager.bookKind = SettingManager.BookKind1;
    

    You should also use Q_ENUM instead of Q_ENUMS.