gpt4 book ai didi

c++ - 如何从 QML 访问 C++ 枚举?

转载 作者:IT老高 更新时间:2023-10-28 12:34:04 27 4
gpt4 key购买 nike

class StyleClass : public QObject {
public:
typedef enum
{
STYLE_RADIAL,
STYLE_ENVELOPE,
STYLE_FILLED
} Style;

Style m_style;
//...
};

.h 文件有上述代码。 如何通过 QML 访问上述枚举?

最佳答案

您可以将枚举包装在派生自 QObject 的类中(并且您可以将其公开给 QML):

style.hpp:

#ifndef STYLE_HPP
#define STYLE_HPP

#include <QtGlobal>
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
// Qt 4
#include <QDeclarativeEngine>
#else
// Qt 5
#include <QQmlEngine>
#endif

// Required derivation from QObject
class StyleClass : public QObject
{
Q_OBJECT

public:
// Default constructor, required for classes you expose to QML.
StyleClass() : QObject() {}

enum EnStyle
{
STYLE_RADIAL,
STYLE_ENVELOPE,
STYLE_FILLED
};
Q_ENUMS(EnStyle)

// Do not forget to declare your class to the QML system.
static void declareQML() {
qmlRegisterType<StyleClass>("MyQMLEnums", 13, 37, "Style");
}
};

#endif // STYLE_HPP

main.cpp:

#include <QApplication>
#include "style.hpp"

int main (int argc, char ** argv) {
QApplication a(argc, argv);

//...

StyleClass::declareQML();

//...

return a.exec();
}

QML 代码:

import MyQMLEnums 13.37
import QtQuick 2.0 // Or 1.1 depending on your Qt version

Item {
id: myitem

//...

property int item_style: Style.STYLE_RADIAL

//...
}

关于c++ - 如何从 QML 访问 C++ 枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20089196/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com