我正在尝试从QML调用Python方法并使用返回值。
QML从Python方法接收undefined。
当传回Python时,它只是一个空字符串。
import sys
from PyQt5.QtCore import QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
class InPython(QObject):
@pyqtSlot(str, )
def login(self, Login):
print(Login)
return "a"
if __name__ == "__main__":
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
context.setContextProperty("main", engine)
engine.load('Main.qml')
win = engine.rootObjects()[0]
inPython = InPython()
context.setContextProperty("loginManger", inPython)
win.show()
sys.exit(app.exec_())
Main.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.0
ApplicationWindow {
width: 800;
height: 600;
ColumnLayout {
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
anchors.margins: 3
spacing: 3
Column {
spacing: 20
anchors.horizontalCenter: parent.horizontalCenter
TextField {
id: login
objectName: "login"
placeholderText: qsTr("Login")
focus: true
Layout.fillWidth: true
onAccepted: {
btnSubmit.clicked()
}
}
Button {
id: btnSubmit
objectName: "btnSubmit"
text: qsTr("Login")
Layout.fillWidth: true
onClicked: {
var a = loginManger.login(login.text);
console.log(a);
loginManger.login(a); // Python recieves ''
if (a === "a"){
login.text = "SUCCESS"
}
}
}
}
}
}
答案 0 :(得分:2)
您还需要告诉您从方法中返回的内容(请注意pyqtslot装饰器中的class InPython(QObject):
@pyqtSlot(str, result=str) # also works: @pyqtSlot(QVariant, result=QVariant)
def login(self, Login):
print(Login)
return "a"
:
result
result - 结果的类型,可以是Python类型的对象,也可以是 指定C ++类型的字符串。这可能只作为关键字给出 参数。
(以及[{"id":0,"name":"Biatrix"},{"id":1,"name":"Bill"},{"id":2,"name":"O-ren"}]
参数)