我想让我的项目保持秩序,因此我考虑将属性从“main.py”文件移至另一个名为“CustomVariables.py”的文件。但现在我收到“TypeError:无法读取未定义的属性‘loaderSource’”。当您取消注释下面代码中的注释时,它可以正常工作,但是我不想在“BG”类中声明属性。有人可以指导我如何正确设置它吗?
自定义变量.py
from PySide6.QtCore import QObject, Property, Signal
class CustomVariables(QObject):
def __init__(self):
QObject.__init__(self)
self.loaderSource = 'PageWork.qml'
def get_loaderSource(self):
return self._loaderSource
def set_loaderSource(self, new_loaderSource):
self._loaderSource = new_loaderSource
self.loaderSourceChanged.emit()
loaderSourceChanged = Signal()
loaderSource = Property(str, get_loaderSource, set_loaderSource, notify=loaderSourceChanged)
主程序
import sys
from pathlib import Path
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import QObject, Property, Signal
from CustomVariables import CustomVariables
class BG(QObject):
def __init__(self):
QObject.__init__(self)
# self.loaderSource = 'PageWork.qml'
cv = CustomVariables()
# def get_loaderSource(self):
# return self._loaderSource
# def set_loaderSource(self, new_loaderSource):
# self._loaderSource = new_loaderSource
# self.loaderSourceChanged.emit()
# loaderSourceChanged = Signal()
# loaderSource = Property(str, get_loaderSource, set_loaderSource, notify=loaderSourceChanged)
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
background = BG()
engine.rootContext().setContextProperty("bg", background)
qml_file = Path(__file__).resolve().parent / "main.qml"
engine.load(qml_file)
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
主文件
import QtQuick.Controls.FluentWinUI3
import QtQuick
Window {
id: root
width: 1280
height: 720
visible: true
Loader {
id: projectLoader
anchors.fill: parent
asynchronous: true
source: bg.cv.loaderSource
//source: bg.loaderSource
}
}
我也尝试在“init”中声明“cv”:
self.cv = CustomVariables()
但仍然没有成功