gpt4 book ai didi

python - PyQt5 && QML 导出枚举

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:17 26 4
gpt4 key购买 nike

是否可以将 enumPython 导出到 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
}
}
}

希望对您有所帮助。

关于python - PyQt5 && QML 导出枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com