Create an enumerator in QML by C ++

1

I'm trying to use an enumerator that was created in C ++ and I'm using the QT 5.6 website itself to guide me, Data Type Conversion Between QML and C ++ . However when compiling I get the following compiler exception:

error: undefined reference to 'TypeSexClass :: staticMetaObject'

Enum

#include<QObject&gtclassTypeSexClass:publicQObject{Q_OBJECTQ_ENUMS(TypeSex)public:enumTypeSex{NONE,MEN,WOMAN};TypeSextypesex()const;};

Main

#include<QGuiApplication>#include<QDebug>#include<QtQml>intmain(intargc,char*argv[]){QGuiApplicationapp(argc,argv);TypeSexClasstypesexclass();qmlRegisterUncreatableType<TypeSexClass>("teste.typesex", 1, 0, "TypeSexClass","It's not do create");

    QQmlApplicationEngine engine;

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Resolved

Enum

#ifndef TYPESEX_H
#define TYPESEX_H

#include <QObject>

class TypeSexClass : public QObject
{
    Q_OBJECT
public:    
    enum TypeSex{
        NONE, MAN, WOMAN};
    Q_ENUM(TypeSex)
};

#endif // TYPESEX_H

Main

#include <QGuiApplication>
#include <QDebug>
#include <QtQml>
#include "typesex.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterUncreatableType<TypeSexClass>("teste.typesex", 1, 0, "TypeSex","It's not instantiable. It's a enumeration");

    QQmlApplicationEngine engine;

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

QML


Window {
    id: window1
    title: "Redi"
    visible: true
    visibility : "Maximized"
    Button {
            id: button1
            x: 457
            width: 100
            height: 50
            text: qsTr("Gerar")
            anchors.top: parent.top
            anchors.topMargin: 33
            onClicked: {                
                console.log(TypeSex.MAN)
                console.log(TypeSex.WOMAN)
                console.log(TypeSex.NONE)
            }
}
    
asked by anonymous 03.06.2016 / 16:27

1 answer

2

Since Qt 5.5 you should use a new macro called Q_ENUM immediately after the enumeration definition. In your case:

enum TypeSex{NONE, MEN, WOMAN};
Q_ENUM(TypeSex)

Note that you no longer need to manually record in the meta class, just use the macro. Much easier! :)

More information in this post .

  

P.S .: Silly preciosity, but use plural or singular in everything in your   definition of the enumeration. Men is in the plural, and Woman in the singular   (use Men and Women , or Man and Woman - which seems to be the   appropriate for the enumeration that you are doing).

    
03.06.2016 / 16:37