我有一个我正在接触QML的课程如下:
#ifndef MYTYPE_H
#define MYTYPE_H
#include <QString>
#include <QObject>
class MyType : public QObject
{
Q_OBJECT
Q_ENUMS(TestEnum)
Q_PROPERTY(TestEnum foo READ foo WRITE setFoo NOTIFY fooChanged)
public:
enum class TestEnum
{
State1 = 1,
State2 = 2
};
MyType(QObject *parent = nullptr) :
QObject(parent),
mFoo(TestEnum::State1)
{
}
TestEnum foo() const
{
return mFoo;
}
void setFoo(TestEnum foo)
{
if (foo == mFoo)
return;
mFoo = foo;
emit fooChanged(mFoo);
}
signals:
void fooChanged(MyType::TestEnum blah);
private:
TestEnum mFoo;
};
Q_DECLARE_METATYPE(MyType::TestEnum)
#endif // MYTYPE_H
这里我有一个枚举类型,我想向QML公开。
我将主要函数调用的类型注册为:
qmlRegisterType<MyType>("App", 1, 0, "MyType");
现在我的qml文件中有一个信号,我接受了这个枚举参数:
signal submitTextField(MyType::TestEnum state) // Compiler complains here
信号连接为:
QObject *topLevel = engine.rootObjects().value(0);
//QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
// This is just a class that implements the slot
HandleTextField handleTextField;
// connect our QML signal to our C++ slot
QObject::connect(topLevel, SIGNAL(submitTextField(MyType::TestEnum)),
&handleTextField, SLOT(handleSubmitTextField(MyType::TestEnum)));
实现槽的类定义为:
class HandleTextField : public QObject
{
Q_OBJECT
public:
explicit HandleTextField(QObject *parent = 0);
public slots:
void handleSubmitTextField(MyType::TestEnum in);
void handleFooChanged(MyType::TestEnum in);
public:
MyType myType;
};
语法MyType::TestEnum
无效。我很想将所有内容转换为ints
并取消枚举,但想知道是否有办法在QML信号中使用此枚举类型。我可以MyType.State1 and MyType.State2
但无法引用枚举类型。
答案 0 :(得分:0)
好吧,似乎这不能用枚举来完成,即你必须使用ints
。我做了以下更改并且有效:
class MyType : public QObject
{
Q_OBJECT
Q_ENUMS(TestEnum)
Q_PROPERTY(TestEnum foo READ foo WRITE setFoo NOTIFY fooChanged)
public:
enum TestEnum
{
State1 = 1,
State2 = 2
};
MyType(QObject *parent = nullptr) :
QObject(parent),
mFoo(TestEnum::State1)
{
}
TestEnum & foo()
{
return mFoo;
}
void setFoo(TestEnum foo)
{
if (foo == mFoo)
return;
mFoo = foo;
emit fooChanged(static_cast<int>(mFoo));
}
signals:
void fooChanged(int blah);
private:
TestEnum mFoo;
};
Q_DECLARE_METATYPE(MyType::TestEnum)
还需要更改插槽:
class HandleTextField : public QObject
{
Q_OBJECT
public:
explicit HandleTextField(QObject *parent = 0);
public slots:
void handleSubmitTextField(int in);
void handleFooChanged(int in);
public:
MyType myType;
};
我们需要更改int
类型的连接:
QObject::connect(topLevel, SIGNAL(submitTextField(int)),
&handleTextField, SLOT(handleSubmitTextField(int)));
最后信号被声明为:
signal submitTextField(int text)