1 回答
TA贡献1798条经验 获得超3个赞
如果你想从 python 返回一个值,那么你必须在 pyqtSlot 中使用“result”:
import os
from PyQt5.QtCore import pyqtProperty, pyqtSlot, QObject, QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
import toml
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class Settings(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self._error_string = ""
@pyqtProperty(str, constant=True)
def errorString(self):
return self._error_string
@pyqtSlot(result=bool)
def hasError(self):
return bool(self.errorString)
@pyqtSlot(str, str, result=str)
def getSettings(self, category, key):
self._error_string = ""
error_string = ""
value = ""
try:
with open(os.path.join(CURRENT_DIR, "settings.toml"), "r") as settings:
toml_object = toml.load(settings)
value = str(toml_object[category][key])
except FileNotFoundError:
error_string = "FileNotFoundError"
except toml.TomlDecodeError:
error_string = "TomlDecodeError"
except Exception as e:
error_string = str(e)
self._error_string = error_string
return value
if __name__ == "__main__":
import sys
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
settings = Settings()
engine.rootContext().setContextProperty("Settings", settings)
filename = os.path.join(CURRENT_DIR, "main.qml")
engine.load(QUrl.fromLocalFile(filename))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow {
visible: true
width: 640
height: 480
Component.onCompleted: {
var value = Settings.getSettings("last-used-font-settings", "font")
if(Settings.hasError()){
console.error(Settings.errorString)
}
else{
console.log(value)
}
}
}
添加回答
举报