Link a QIcon provided by a class derived from QAbstractListModel to QML Image

advertisements

I try to bind a QIcon provided by a class derived from QAbstractListModel to QML Image like this:

Component {
    id: myDelegate
    //...
            Column {
                anchors.verticalCenter: parent.verticalCenter
                spacing: 5

                Image {
                    source: model.DecorationRole
                }

                Text {
                    text: model.DisplayRole
    //...
}

But this results in this error:

Unable to assign QIcon to QUrl

How to do this correctly?


You can not assign a QIcon as a source of a QML Image.

What you need to do is choose a custom URL format for your icons, e.g.

images://myicons/<icon_id>

This string is what you set as a URL for Image.source.

Now you create and register an imageprovider, that delivers the icon when you send the requested URL from QML:

  • Create a subclass of QQuickImageProvider, e.g. MyIconProvider
  • Overwrite the function requestPixmap that takes the id as and argument and returns pixel data

Then you register the image provider in your main.cpp

MyIconProvider *mip = new MyIconProvider();
engine.addImageProvider("myicons", mip);