2016-03-24 8 views
0

Ich versuche, eine Python-Methode von QML aufrufen und den Rückgabewert verwenden.Erhalten Rückgabewert in QML von Python-Methode

QML empfängt undefined, von der Python-Methode.

Bei der Rückgabe an Python ist es nur eine leere Zeichenfolge.

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" 
        } 
       } 
      } 
     } 
    } 
} 

Antwort

1

Sie müssen auch sagen, was Sie von Ihrer Methode zurückkehren (achten Sie auf die result im pyqtslot Dekorateur:

class InPython(QObject): 
    @pyqtSlot(str, result=str) # also works: @pyqtSlot(QVariant, result=QVariant) 
    def login(self, Login): 
     print(Login) 
     return "a" 

Ergebnis - Der Typ des Ergebnisses und möglicherweise ein Objekt vom Typ Python oder ein String, der einen C++ - Typ angibt nly als ein Schlüsselwort Argument gegeben werden.

Documentation about @pyqtslot (und der result Parameter)