Skip to main content
 首页 » 编程设计

python之PyQt5 && QML 导出枚举

2025年05月04日10shanyou

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

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 引擎注册的类中定义,它就可以正常工作。这是一个小例子:

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

希望对您有所帮助。