Search code examples
classreturn

Return data from class


I'm new and need some advice. I am working on a smart home project and used QT Creator for graphical visualization.

Managed to get the button from QML to Python, but I don't know how to get from the class Foo to the row outside the class to the RESULT ( the value of the button must be in the result ).

Thank you for your help..

class Foo(QObject):
    @Slot(str)
    def button_slot(self,button_from_qml : str, ):
        xprint(input_string)
        return button_from_qml
    
result = Foo.test_slot()

print(result)


if __name__ == "__main__":
    import sys

    app = QGuiApplication()
    foo = Foo()
    engine = QQmlApplicationEngine()

    qml_file = "main.qml"
    current_dir = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(current_dir, qml_file)
    engine.load(QUrl.fromLocalFile(filename))
    if not engine.rootObjects():
        sys.exit(-1)

    engine.rootObjects()[0].button_off.connect(foo.button_slot, type=Qt.ConnectionType.QueuedConnection)

Managed to get the button from QML to Python, but I don't know how to get from the class Foo to the row outside the class to the RESULT ( the value of the button must be in the result ).

My request - image


Solution

  • Assuming that there is a different test_slot() function in the Foo class (in the future please include all relevant code), this would work. You have to initialize the Foo object before calling a method on it.

    class Foo(QObject):
        @Slot(str)
        def button_slot(self,button_from_qml : str, ):
            xprint(input_string)
            return button_from_qml
        
    result = Foo().test_slot()
    
    print(result)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QGuiApplication()
        foo = Foo()
        engine = QQmlApplicationEngine()
    
        qml_file = "main.qml"
        current_dir = os.path.dirname(os.path.realpath(__file__))
        filename = os.path.join(current_dir, qml_file)
        engine.load(QUrl.fromLocalFile(filename))
        if not engine.rootObjects():
            sys.exit(-1)
    
        engine.rootObjects()[0].button_off.connect(foo.button_slot, type=Qt.ConnectionType.QueuedConnection)