Zak
Zak

Reputation: 484

QML: How to delete a global QSGTexture object?

I have QQuickItem derived class (MyItem) which just draws a texture (QSGTexture). Because all MyItem's drawing the same texture I have shared one QSGTexture instance between all of them. This instance is created on first access:

QSGTexture *MyItem::getGlobalTexture()
{
    static auto tex = window->createTextureFromImage(QImage{s_textureName});
    return tex;
}

Everyting fine with it but I want somehow to delete this texture on app destruction.

My first idea was to set some parent to it and I have chosen a QQuickWindow, but it is not possible because they live on different threads:

window - mainThread, tex - SGRenderThread

Another way is to delete it in MyApp destructor, but this call will also be from the mainThread and SGRenderThread may be already deleted.

One more idea is to use QCoreApplication::aboutToQuit signal with a QueuedConnection type, so the deleting will happen on the SGRenderThread if it still exists and will not be drawing any more frames.

What is the best and right way to delete a global QSGTexture object?

Upvotes: 2

Views: 299

Answers (1)

Zak
Zak

Reputation: 484

I've come to the following solution what is actually the third idea from the question and it seems to work for both threaded and not threaded Scene Graph

QSGTexture *MyItem::getGlobalTexture(QQuickWindow *window)
{
    static QSGTexture *texture = [window]{
        auto tex = window->createTextureFromImage(QImage{s_textureName});
        //will delete the texture on the GSthread 
        QObject::connect(qApp, &QCoreApplication::aboutToQuit, tex, [tex]{ tex->deleteLater(); });
        return tex;
    }();
    return texture;
}

Upvotes: 1

Related Questions