1

I have been looking for a way to update images on my QML UI from my PyQt code. The closest answer I could find was from Grecko Update ImageView in QML

// Code from Stackoverflow Link 
// MyImage.qml
    Image {
        cache: false
        function reload() {
            var tmpSource = source;
            source = "";
            source = tmpSource;
        }
    }

I would like to apply that solution (or any solution) to my project. Below is some sample code that is similar to my implementation.

#test.py
    import sys
    from PyQt5.QtCore import QObject, QUrl
    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtQuick import QQuickView
    from PyQt5.QtQml import QQmlApplicationEngine


    if __name__ == '__main__':
        myApp = QApplication(sys.argv)

        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty("main", engine)

        engine.load('main.qml')

        win = engine.rootObjects()[0]
        image = win.findChild(QObject, "myimage")
        #What do with the image here?

        win.show()

        sys.exit(myApp.exec_())

Here is the QML code.

//test.qml
Image {
        id: image1
        objectName: "myimage"
        x: 384
        y: 403
        width: 100
        height: 100
        source: ""
    }

I am still fairly new to PyQT5 and QML so if someone has a basic example that shows how I can implement this or can edit my basic example, it would be greatly appreciated.

Thank you :)

Community
  • 1
  • 1
Knoose
  • 113
  • 4
  • 11

1 Answers1

1

If you want to reload all images via your MyImage type, then one option is to use the setContextProperty() mechanism to expose an Python object with a signal and use that signal in MyImage.qml to trigger the reload() function.

In Python:

reloader = ObjectWithAReloadSignal()
context.setContextProperty("_reloader", reloader);

in MyImage.qml

Image {
    id: image

    void reload() { ... }

    Connections {
        target: _reloader
        onReloadImages: image.reload()
    }
}

The assumption here is that the ObjectWithAReloadSignal has a signal called reloadImages() which ti emits when QML should trigger the reload.

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22