Reputation: 16765
Is it possible to export enum
from Python
to QML
instance?
class UpdateState():
Nothing = 0
CheckingUpdate = 1
NoGameFound = 2
Updating = 3
How I want to use it in qml
:
import PythonController 1.0
PythonController {
id: controller
}
Item {
visible: controller.UpdateState.Nothing ? true : false
}
Upvotes: 4
Views: 1195
Reputation: 1484
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
}
}
}
Hope that helps.
Upvotes: 2