从 Python 调用 QML 函数

Call QML function from Python

我需要从 QML(在本例中是从 textInput)获取信息,对其进行一些操作,并根据操作结果调用 QML 中的适当函数。我知道如何从 textInput 获取文本,但无法找到如何回复,具体取决于结果。这是我的代码:

main.qml:

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    TextInput {
        id: textInput
        x: 280
        y: 230
        width: 80
        height: 20
        text: qsTr("Text Input")
        font.pixelSize: 12
        horizontalAlignment: Text.AlignHCenter
        selectByMouse: true
    }

    Dialog {
        id: dialog1
        modal: true
        title: "OK"
        Text {text: "Everything is OK!"}
        x: parent.width/2 - width/2
        y: parent.height/2 - height/2
    }

    Dialog {
        id: dialog2
        modal: true
        title: "ERROR"
        Text {text: "Check Internet connection!"}
        x: parent.width/2 - width/2
        y: parent.height/2 - height/2
    }

    Button {
        id: button
        x: 270
        y: 318
        text: qsTr("Check")
        onClicked: {
            bridge.check_tI(textInput.text)
        }
    }
}

main.py:

import sys
import os

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QObject, Slot, Signal, Property

class Bridge(QObject):

    @Slot(str)
    def check_tI(self, tf_text):
        try:
            # SOME OPERATIONS
            # MUST BE DONE IN PYTHON
            # IF EVERYTHING OK:
            # dialog1.open()
            print("OK! ", tf_text)
        except:
            # dialog2.open()
            print("ERROR! ", tf_text)



if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    bridge = Bridge()
    engine.rootContext().setContextProperty("bridge", bridge)

    engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))

    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

一种可能是 return 一个布尔值,可用于决定显示一个或另一个对话框。

class Bridge(QObject):
    @Slot(str, <b>result=bool</b>)
    def check_tI(self, tf_text):
        try:
            # trivial demo
            import random

            assert random.randint(0, 10) % 2 == 0
            print("OK! ", tf_text)
        except:
            print("ERROR! ", tf_text)
            <b>return False</b>
        else:
            <b>return True</b>
onClicked: {
    if(bridge.check_tI(textInput.text)){
        dialog1.open()
    }
    else{
        dialog2.open()
    }
}