PyQt5和&&QML导出枚举 [英] PyQt5 && QML exporting enum

查看:88
本文介绍了PyQt5和&&QML导出枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 enum Python 导出到 QML 实例?

Is it possible to export enum from Python to QML instance?

class UpdateState():
    Nothing = 0
    CheckingUpdate = 1
    NoGameFound = 2
    Updating = 3

我想如何在 qml 中使用它:

import PythonController 1.0

PythonController {
    id: controller
}

Item {
    visible: controller.UpdateState.Nothing ? true : false
}

推荐答案

只要枚举已在 Q_ENUMS 中注册并在向QML引擎注册的类中定义,它就可以正常工作.这是一个小例子:

It works fine, as long as the enum is registered with Q_ENUMS and defined inside a class registered with the QML engine. Here's a small example:

example.py

from sys import exit, argv

from PyQt5.QtCore import pyqtSignal, pyqtProperty, Q_ENUMS, QObject
from PyQt5.QtQml import QQmlApplicationEngine, qmlRegisterType
from PyQt5.QtGui import QGuiApplication


class Switch(QObject):

    class State:
        On = 0
        Off = 1

    Q_ENUMS(State)

    stateChanged = pyqtSignal(State, arguments=['state'])

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._state = Switch.State.Off

    @pyqtProperty(State, notify=stateChanged)
    def state(self):
        return self._state

    @state.setter
    def state(self, state):
        if state != self._state:
            self._state = state
            self.stateChanged.emit(self._state)


app = None


def main():
    global app

    app = QGuiApplication(argv)

    qmlRegisterType(Switch, 'Switch', 1, 0, 'Switch')

    engine = QQmlApplicationEngine()
    engine.load('example.qml')

    exit(app.exec_())


if __name__ == '__main__':
    main()

example.qml

import QtQuick 2.0
import QtQuick.Window 2.0

import Switch 1.0

Window {
    title: 'QML Enum Example'
    visible: true
    width: 400
    height: 400

    color: colorSwitch.state === Switch.On ? "green" : "red"

    Switch {
        id: colorSwitch
        state: Switch.Off
    }

    Text {
        text: "Press window to switch state"
    }

    MouseArea {
        anchors.fill: parent

        onClicked: {
            if (colorSwitch.state === Switch.Off)
                colorSwitch.state = Switch.On
            else
                colorSwitch.state = Switch.Off
        }
    }
}

希望有帮助.

这篇关于PyQt5和&&QML导出枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆