【QML】qml中使用枚举(enum)

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);
    }

}

在这里插入图片描述

参考

  1. QML(19)——枚举量enum的使用
  2. QML新功能——自定义枚举
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值