1. 方法1(C++中定义)
C++注册枚举给QML使用。
1.1. 代码
1.1.1 C++代码
- EnumTest.h
// EnumTest.h
#ifndef ENUMTEST_H
#define ENUMTEST_H
#include <QObject>
class EnumTest : public QObject
{
Q_OBJECT
public:
enum class MyEnum {
Case1 = 1, // 首字母必须大写
Case2,
Case3,
};
Q_ENUM(MyEnum)
explicit EnumTest(QObject *parent = nullptr);
#endif // ENUMTEST_H
- EnumTest.cpp
// EnumTest.cpp
#include "enumtest.h"
EnumTest::EnumTest(QObject *parent)
: QObject{parent}
{
}
- main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "enumtest.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// 注册 EnumTest
qmlRegisterType<EnumTest>("com.custom", 1, 0, "EnumTest");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
1.1.2 QML中使用
import QtQuick 2.15
import com.custom 1.0
Rectangle{
width: 50
height: 50
color: "grey"
MouseArea {
anchors.fill: parent
onClicked: {
//下面两种方法都可以
console.log("Enum out: ", EnumTest.MyEnum.Case1)
console.log("Enum out: ", EnumTest.Case1)
}
}
}
//输出: Enum out: 1
2. 方法2(qml中定义枚举)
QML新功能——自定义枚举:
https://blog.csdn.net/sksukai/article/details/104514187
//EnumBtn.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
Button {
enum EnumTest{
Enum1 = 5,
Enum2
}
onClicked: {
console.log(EnumBtn.EnumTest.Enum2);
}
}