如何将枚举类传递给 QML?
我正在学习使用 Qt 来学习 QML,但在将 enum class
传递给 qml
时遇到了一些麻烦.
I am on learning to QML with Qt and get some trouble with passing enum class
to qml
.
当我使用带有 int
参数的信号时 - 没关系,代码可以完美运行.
When I use signal with int
parameters - it's all right and code work perfectly.
但是,这里有麻烦,如果我使用带有一些 enum class
参数的信号,我在 qml 信号处理程序中有 undefined
值.我试图通过 qmlRegisterType
注册 enum class
但它不起作用.我将不胜感激.
But, and here the trouble, if I use signal with some enum class
parameters I have undefined
values in qml signal handler. I tried to register enum class
through qmlRegisterType
but it's not working. I will be grateful for the help.
代码如下:
一些 Helper
类
class Helper : public QObject
{
Q_OBJECT
Q_ENUMS(Requester)
Q_ENUMS(JANSWER)
public:
enum class Requester {
ReqLogin,
ReqNull,
ReqSave,
ReqError,
ReqUnknown
};
enum class JANSWER {
OK,
Complete,
Error,
Unknown
};
};
ma??in.cpp
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<JsonPackWorker>("com.jsonpackworker", 1, 0, "JsonPackWorker");
qmlRegisterType<Helper>("com.Helper", 1, 0, "Helper");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
JsonPackWorker.h
class JsonPackWorker : public QObject
{
Q_OBJECT
public:
<...>
signals:
<...>
void sendAnswer(Helper::Requester req, Helper::JANSWER answer);
public slots:
<...>
};
JsonPackWorker.cpp 中的某处
emit sendAnswer(Helper::Requester::ReqNull, Helper::JANSWER::OK);
ma??in.qml
<...>
import com.jsonpackworker 1.0
import com.Helper 1.0
ApplicationWindow {
id: mainWindow
// Requests in answers
property int reqLogin: Helper.ReqLogin
<...>
JsonPackWorker {
id: packWorker
<...>
onSendAnswer: {
// Here I've got undefined undefined if there enum class parameters
console.log(req + " " + answer)
switch(req) {
case reqLogin: loginDial.checkLogin(answer)
break;
default:
}
}
}
}
推荐答案
问题出在 Helper
类中(感谢 Qt 社区).
The problem was in Helper
class (thanks to Qt community).
class Helper {
...
};
Q_DECLARE_METATYPE(Helper::Requester)
Q_DECLARE_METATYPE(Helper::JANSWER)
相关文章