Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend QML Image type with an update function

As most people familiar with QML know, there is no builtin "refresh" functionality in QML Image.

I would like to create a new QML type, say RefreshableImage to alleviate this problem without resorting to changing the source, which I feel is an ugly hack, as it bleeds into all layers of the Model-View relationship and this switching behaviour is unnatural. Additionally, setting a different source on an Image breaks any binding that may have been set (which is really the core of the problem: I want an updateable image that maintains its binding, and is isolated to QML). I understand I'll need to call some signal to actually refresh the image, that's fine.

I have trouble finding documentation on a way to extend Qt's own Image so that I can force it to reload its source. I would like to avoid writing a complete component that mostly badly replicates Image to add one function. Is there a way to extend a builtin component like I have in mind?

Minor notes:

  • due to external circumstances, I'm limited to Qt 5.5.
  • We use as source a UUID of the underlying image object which is used by an QQuickImageProvider to get the actual QImage. Hence I don't want to change this when updating an image.
like image 256
rubenvb Avatar asked Jan 25 '26 17:01

rubenvb


1 Answers

You could create a RefreshableImage type that hides the ugly source changing from you.

There's a simple way of doing it by introducing a new property for the source :

import QtQuick 2.0

Image {
    id: root
    property string refreshableSource
    source: refreshableSource
    function refresh() {
        source = "";
        source = Qt.binding(function() { return refreshableSource });
    }
}

You have to use it like that : RefreshableImage { refreshableSource: "image.jpg" }.

If you want to still use source as a property, you could do it with some aliases shenanigans. Since aliases are only activated once a component has been fully initialized, you can overwrite the source property of Image but still be able to access the underlying one.

import QtQuick 2.0

Image {
    id: root
    property alias actualUnderlyingSource: root.source //this refers to Image.source and not the newly created source alias
    property alias source: root.refreshableSource
    property string refreshableSource
    actualUnderlyingSource: refreshableSource
    function refresh() {
        actualUnderlyingSource = "";
        actualUnderlyingSource = Qt.binding(function() { return refreshableSource });
    }
}

You could then use it like so RefreshableImage { source: "image.jpg" }, this will in fact modify the refreshableSource property

like image 83
GrecKo Avatar answered Jan 28 '26 09:01

GrecKo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!