[英]Can't bind a Python function to a QML button
I've been struggling with binding QT Quick Application front-end and back-end.我一直在努力绑定 QT 快速应用程序前端和后端。 Here's my code.
这是我的代码。 For a clear and short example the function prints "Hello from back-end" as an output without getting any arguments.
对于一个清晰而简短的示例,function 将“Hello from back-end”打印为 output 而没有得到任何 arguments。
main.py主程序
from pathlib import Path
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine, QmlElement
from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot
class Calculator(QObject):
def __init__(self):
QObject.__init__(self)
@pyqtSlot()
def greet(self):
print("Hello from backend")
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
backend = Calculator()
engine.rootContext().setContextProperty("backend", backend)
engine.load("main.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())
main.qml主要.qml
import QtCore
import QtQuick
import QtQuick.Controls
import QtQuick.Dialogs
ApplicationWindow {
id: mainWindow
...
Button {
objectName: "checkButton"
id: modelCheck
text: qsTr("Check model")
onClicked: backend.greet()
}
Connections {
target: backend
function onSignalPrintTxt(boolValue) {
return
}
}
}
When running this code, I get the following error:运行此代码时,出现以下错误:
TypeError: Property 'greet' of object QVariant(PySide::PyObjectWrapper, 0x1006571f0) is not a function
What am I doing wrong?我究竟做错了什么?
You appear to mixing pyside with pyqt.您似乎将 pyside 与 pyqt 混合在一起。
To make a pyside only solution, I use QObject and Slot from pyside and updated the signature of greet.为了制作仅 pyside 的解决方案,我使用 pyside 的 QObject 和 Slot 并更新了 greet 的签名。 The rest of the code is your code.
密码的rest就是你的密码。
# main.py
import sys
from pathlib import Path
from PySide6.QtCore import Qt, QObject, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
class Calculator(QObject):
def __init__(self):
QObject.__init__(self)
@Slot()
def greet(self):
print("Hello from backend")
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
backend = Calculator()
engine.rootContext().setContextProperty("backend", backend)
qml_file = Path(__file__).parent / "main.qml"
engine.load(qml_file)
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
// main.qml
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Window
ApplicationWindow {
id: main
title: qsTr("Hello World")
width: 640
height: 480
visible: true
Button {
id: modelCheck
text: qsTr("Check model")
onClicked: backend.greet()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.