在 qml 中使用 C++ 枚举

Using c++ enum in qml

我在 qml

中使用了一个 enum
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();
};

main.cpp我注册了SettingManager

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

我在qml文件中使用这个

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

TabBarCurrentIndex 更改时发生以下错误:

Error: Cannot assign [undefined] to int

您将类型注册为 SettingManager,但将其用作 BookManager。正确的代码是:

settingManager.bookKind = SettingManager.BookKind1;

您还应该使用