dany
dany

Reputation: 359

Call QML function from Python

I need to take informations from QML (from textInput in this case), make some operations on it and depending what is the operations result call appropriate function in QML. I know how to get the text from textInput, but can't find out how to response back, depending on the results. Here is my code:

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_())

Upvotes: 1

Views: 1122

Answers (1)

eyllanesc
eyllanesc

Reputation: 244132

One possible is to return a boolean that can be used to make the decision to show one or the other dialog.

class Bridge(QObject):
    @Slot(str, result=bool)
    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)
            return False
        else:
            return True
onClicked: {
    if(bridge.check_tI(textInput.text)){
        dialog1.open()
    }
    else{
        dialog2.open()
    }
}

Upvotes: 1

Related Questions