Pyqt5 && Qml Exporting Enum
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
Solution 1:
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
classSwitch(QObject):
classState:
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)defstate(self):
return self._state
@state.setterdefstate(self, state):
if state != self._state:
self._state = state
self.stateChanged.emit(self._state)
app = Nonedefmain():
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 Switch1.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.
Post a Comment for "Pyqt5 && Qml Exporting Enum"