How to set a QML instantiated item as a QImageProvider

230 views Asked by At

I have a class that inherits QQuickItem and QQuickImageProvider. This class is instantiated from qml. I need to call QQmlEngine::addImageProvider so that this class can actually provide images. I should be able to get the engine that my object exists in as described in this question. In the constructor of my class I'm calling

QQmlEngine *engine = nullptr;
QQmlContext *context = QQmlEngine::contextForObject(this);
if (context)
    engine = context->engine();
if (engine)
    engine->addImageProvider("MyImageProvider", this);

But QQmlEngine::contextForObject(this); always returns a null pointer. Why does this not work?

1

There are 1 answers

1
DJMcMayhem On

I figured it out. Calling QQmlEngine::contextForObject(this); in the constructor doesn't work, I'm guessing because the object isn't done being constructed yet. If I make a Q_INVOKABLE function to register it later

void MyImageProvider::registerImageProvider()
{
    QQmlEngine *engine = nullptr;
    QQmlContext *context = QQmlEngine::contextForObject(this);
    if (context)
        engine = context->engine();
    if (engine) {
        engine->removeImageProvider("MyImageProvider");
        engine->addImageProvider("MyImageProvider", this);
    }
}

and then in my QML:

ImageProvider {
    id: myClass

    Component.onCompleted: myClass.registerImageProvider();
}

Then that works like a charm.