无法连接到 Python 发出的 QML 中的信号
Unable to connect to signal in QML emitted from Python
我在 Python 中创建了一个 QQuickItem
class:
class MyPage(QQuickItem):
def __init__(self, parent=None) -> None:
super().__init__(parent)
error_encountered = Signal(str)
@QtCore.Slot(QUrl, result=None)
def load_report(self, file_path: QUrl) -> None:
print(f"Called with: {file_path}")
self.error_encountered.emit("Uh oh!")
以上class注册为:
qmlRegisterType(MyPage, "MyPage", 1, 0, "MyPage")
我的 QML 看起来像:
MyPage {
signal errorEncountered(string text)
Component.onCompleted: error_encountered.connect(errorEncountered)
onErrorEncountered: console.log(text)
}
但是,我收到以下错误:
qrc:/qml/main.qml:93: ReferenceError: error_encountered is not defined
PySide2 将信号从 QML 连接到源代码的模式在 Python 中与 C++ 有点不同,我无法弄明白。在 C++ 中,我会定义一个像 void errorEncountered(const QString& errorMessage);
这样的信号,而在我的 QML 中,我可以简单地完成 onErrorEncountered: console.log(errorMessage)
.
信号被声明为class的属性,也就是说,它们不应该在class的任何方法中创建。解决方案是:
class MyPage(QQuickItem):
error_encountered = Signal(str) # <---
def __init__(self, parent=None) -> None:
super().__init__(parent)
@QtCore.Slot(QUrl, result=None)
def load_report(self, file_path: QUrl) -> None:
print(f"Called with: {file_path}")
self.error_encountered.emit("Uh oh!")
我在 Python 中创建了一个 QQuickItem
class:
class MyPage(QQuickItem):
def __init__(self, parent=None) -> None:
super().__init__(parent)
error_encountered = Signal(str)
@QtCore.Slot(QUrl, result=None)
def load_report(self, file_path: QUrl) -> None:
print(f"Called with: {file_path}")
self.error_encountered.emit("Uh oh!")
以上class注册为:
qmlRegisterType(MyPage, "MyPage", 1, 0, "MyPage")
我的 QML 看起来像:
MyPage {
signal errorEncountered(string text)
Component.onCompleted: error_encountered.connect(errorEncountered)
onErrorEncountered: console.log(text)
}
但是,我收到以下错误:
qrc:/qml/main.qml:93: ReferenceError: error_encountered is not defined
PySide2 将信号从 QML 连接到源代码的模式在 Python 中与 C++ 有点不同,我无法弄明白。在 C++ 中,我会定义一个像 void errorEncountered(const QString& errorMessage);
这样的信号,而在我的 QML 中,我可以简单地完成 onErrorEncountered: console.log(errorMessage)
.
信号被声明为class的属性,也就是说,它们不应该在class的任何方法中创建。解决方案是:
class MyPage(QQuickItem):
error_encountered = Signal(str) # <---
def __init__(self, parent=None) -> None:
super().__init__(parent)
@QtCore.Slot(QUrl, result=None)
def load_report(self, file_path: QUrl) -> None:
print(f"Called with: {file_path}")
self.error_encountered.emit("Uh oh!")