[SOLVED] How to create QML Image Element from a QImage Object (C++)?

  • How can I convert a QImage into a QML Element? I can't use the Image QML Element because the source property requires an URL and I only have the actual QImage in memory.

    The only way I could come up with so far is to extend the QDeclarativeItem and render the image. It is far from ideal because then I can't make use of the capabilities of the QML Image element.


  • Hi,

    You can use "QDeclarativeImageProvider":http://doc.qt.nokia.com/4.7/qdeclarativeimageprovider.html to load a QImage into an Image element.


  • Michael,
    Thanks, it worked. It is not as straight forward as I would expect for something that looks like a very common scenario (e.g. a model view with QImage returned for the DecorationRole) but will do.

  • Yes, it's less than ideal. Originally we allowed setting a QPixmap directly on the Image element, but there were memory management issues with that approach. QDeclarativeImageProvider was the solution we came up with to those issues for 4.7 -- it may be that a better solution is possible in future releases.

    Please let us know if you have any suggestions.

  • Michael,
    Unfortunately I don't know the details about how Qt manage memory so can't even guess the best way to implement but I can think of two user case scenarios:

    1. When you have a "legacy" model with images, you would want to initialize the Image Element with the QImage doing something hopefully as simple as this:

    @Image {
    sourceX: modelData.decorationRole;

    1. On a little more sophisticated user case you could have a c++ class like:
      @class A : public QObject {
      Q_PROPERTY(QImage image READ image NOTIFY imageChanged)

    set the context property:

    @ui->view->rootContext()->setContextProperty("myA", new A());@

    and then you could bind the QImage on QML:

    @Image {
    sourceWithBinding: myA.image;

    so the QML Image element could be notified of changes on the property (for example as result of the C++ app generating a new graph as result of the user input)

  • It's maybe too late but I wrote an article about this and it can maybe help someone.


    It's in french but easily too translate with tools, and the code can be usefull.

Log in to reply