On this page

Scene Graph - Vulkan Under QML

Shows how to render directly with Vulkan under a Qt Quick scene.

The Vulkan Under QML example draws custom Vulkan content under a Qt Quick scene. A custom QQuickItem creates a renderer. The renderer gets the Vulkan device, the render pass, and the command buffer from QSGRendererInterface and records its draw call before the scene graph draws the Qt Quick items. A QML animation changes the size of the squircle. Read this example to learn how to mix native Vulkan rendering with Qt Quick.

Animated squircle rendered with Vulkan under Qt Quick scene with text overlay

Running the Example

You can run the example from:

What to look for

Connecting to the render signals

When the item gets a window, it connects QQuickWindow::beforeSynchronizing() to VulkanSquircle::sync() and QQuickWindow::sceneGraphInvalidated() to VulkanSquircle::cleanup(). Both connections use Qt::DirectConnection, so the slots run on the render thread that emits the signals:

void VulkanSquircle::handleWindowChanged(QQuickWindow *win)
{
    if (win) {
        connect(win, &QQuickWindow::beforeSynchronizing, this, &VulkanSquircle::sync, Qt::DirectConnection);
        connect(win, &QQuickWindow::sceneGraphInvalidated, this, &VulkanSquircle::cleanup, Qt::DirectConnection);

        // Ensure we start with cleared to black. The squircle's blend mode relies on this.
        win->setColor(Qt::black);
    }
}

The VulkanSquircle::sync() function runs on the render thread while the GUI thread is blocked. With the basic render loop, there is no separate render thread, and the function runs on the GUI thread. The function creates the renderer, connects the renderer to the render signals, and copies the QML property values to the renderer:

void VulkanSquircle::sync()
{
    if (!m_renderer) {
        m_renderer = new SquircleRenderer;
        // Initializing resources is done before starting to record the
        // renderpass, regardless of wanting an underlay or overlay.
        connect(window(), &QQuickWindow::beforeRendering, m_renderer, &SquircleRenderer::frameStart, Qt::DirectConnection);
        // Here we want an underlay and therefore connect to
        // beforeRenderPassRecording. Changing to afterRenderPassRecording
        // would render the squircle on top (overlay).
        connect(window(), &QQuickWindow::beforeRenderPassRecording, m_renderer, &SquircleRenderer::mainPassRecordingStart, Qt::DirectConnection);
    }
    m_renderer->setViewportSize(window()->size() * window()->devicePixelRatio());
    m_renderer->setT(m_t);
    m_renderer->setWindow(window());
}

These connections also use Qt::DirectConnection.

Getting the native Vulkan objects

The scene graph emits QQuickWindow::beforeRendering() at the start of each frame, before the main render pass starts. In the first frame, the renderer queries the Vulkan objects that the scene graph uses:

    QSGRendererInterface *rif = m_window->rendererInterface();
    QVulkanInstance *inst = reinterpret_cast<QVulkanInstance *>(
                rif->getResource(m_window, QSGRendererInterface::VulkanInstanceResource));
    Q_ASSERT(inst && inst->isValid());

    m_physDev = *reinterpret_cast<VkPhysicalDevice *>(rif->getResource(m_window, QSGRendererInterface::PhysicalDeviceResource));
    m_dev = *reinterpret_cast<VkDevice *>(rif->getResource(m_window, QSGRendererInterface::DeviceResource));
    Q_ASSERT(m_physDev && m_dev);

    m_devFuncs = inst->deviceFunctions(m_dev);
    m_funcs = inst->functions();
    Q_ASSERT(m_devFuncs && m_funcs);

    VkRenderPass rp = *reinterpret_cast<VkRenderPass *>(
                rif->getResource(m_window, QSGRendererInterface::RenderPassResource));
    Q_ASSERT(rp);

The renderer uses the QVulkanInstance, the physical device, and the device of the scene graph. The renderer creates its graphics pipeline with the render pass of the scene graph, so that the pipeline works in the main render pass.

Recording the draw call

The scene graph emits QQuickWindow::beforeRenderPassRecording() after the main render pass starts and before the scene graph records the commands for the Qt Quick items. In response, the SquircleRenderer::mainPassRecordingStart() function records the draw call:

void SquircleRenderer::mainPassRecordingStart()
{
    // This example demonstrates the simple case: prepending some commands to
    // the scenegraph's main renderpass. It does not create its own passes,
    // rendertargets, etc. so no synchronization is needed.

    const QQuickWindow::GraphicsStateInfo &stateInfo(m_window->graphicsStateInfo());
    QSGRendererInterface *rif = m_window->rendererInterface();

    VkDeviceSize ubufOffset = stateInfo.currentFrameSlot * m_allocPerUbuf;
    void *p = nullptr;
    VkResult err = m_devFuncs->vkMapMemory(m_dev, m_ubufMem, ubufOffset, m_allocPerUbuf, 0, &p);
    if (err != VK_SUCCESS || !p)
        qFatal("Failed to map uniform buffer memory: %d", err);
    float t = m_t;
    memcpy(p, &t, 4);
    m_devFuncs->vkUnmapMemory(m_dev, m_ubufMem);

    m_window->beginExternalCommands();

    // Must query the command buffer _after_ beginExternalCommands(), this is
    // actually important when running on Vulkan because what we get here is a
    // new secondary command buffer, not the primary one.
    VkCommandBuffer cb = *reinterpret_cast<VkCommandBuffer *>(
                rif->getResource(m_window, QSGRendererInterface::CommandListResource));
    Q_ASSERT(cb);

    // Do not assume any state persists on the command buffer. (it may be a
    // brand new one that just started recording)

    m_devFuncs->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline);

    VkDeviceSize vbufOffset = 0;
    m_devFuncs->vkCmdBindVertexBuffers(cb, 0, 1, &m_vbuf, &vbufOffset);

    uint32_t dynamicOffset = m_allocPerUbuf * stateInfo.currentFrameSlot;
    m_devFuncs->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipelineLayout, 0, 1,
                                        &m_ubufDescriptor, 1, &dynamicOffset);

    VkViewport vp = { 0, 0, float(m_viewportSize.width()), float(m_viewportSize.height()), 0.0f, 1.0f };
    m_devFuncs->vkCmdSetViewport(cb, 0, 1, &vp);
    VkRect2D scissor = { { 0, 0 }, { uint32_t(m_viewportSize.width()), uint32_t(m_viewportSize.height()) } };
    m_devFuncs->vkCmdSetScissor(cb, 0, 1, &scissor);

    m_devFuncs->vkCmdDraw(cb, 4, 1, 0, 0);

    m_window->endExternalCommands();
}

To record native commands, call QQuickWindow::beginExternalCommands() before the commands and QQuickWindow::endExternalCommands() after the commands. Always call both functions as a pair. Query the command buffer after the call to QQuickWindow::beginExternalCommands(). The command buffer can be a new secondary command buffer, so do not assume that any state persists. Set all the state that the draw call needs. To draw on top of the Qt Quick scene instead, connect to QQuickWindow::afterRenderPassRecording().

The uniform buffer has one slot for each frame in flight. The renderer uses QQuickWindow::graphicsStateInfo() to select the slot for the current frame.

The graphics pipeline blends the squircle colors additively with the colors in the framebuffer. The scene graph clears the framebuffer at the start of the main render pass, so the result depends on the clear color. For this reason, the item sets the clear color of the window to black in VulkanSquircle::handleWindowChanged().

Animating the shader input

The VulkanSquircle.t property controls the squircle size. The QML code animates the property between 0 and 1. In each frame, the renderer writes the value into the uniform buffer of the shader:

import QtQuick
import VulkanUnderQML

Item {
    id: root

    width: 320
    height: 480

    VulkanSquircle {
        SequentialAnimation on t {
            NumberAnimation { to: 1; duration: 2500; easing.type: Easing.InQuad }
            NumberAnimation { to: 0; duration: 2500; easing.type: Easing.OutQuad }
            loops: Animation.Infinite
            running: true
        }
    }
Releasing the resources

The renderer owns the Vulkan resources, and its destructor releases them. The example deletes the renderer on the render thread. Two cases need handling:

  • When the scene graph releases its graphics resources, it emits QQuickWindow::sceneGraphInvalidated(), which calls VulkanSquircle::cleanup().
  • When the item leaves the window, the scene graph calls QQuickItem::releaseResources(). The VulkanSquircle::releaseResources() function schedules a job that deletes the renderer on the render thread.

Connecting to QQuickWindow::sceneGraphInvalidated() alone does not cover both cases. The GUI thread can delete the item before the job runs, so the job stores only the renderer:

void VulkanSquircle::cleanup()
{
    delete m_renderer;
    m_renderer = nullptr;
}

class CleanupJob : public QRunnable
{
public:
    CleanupJob(SquircleRenderer *renderer) : m_renderer(renderer) { }
    void run() override { delete m_renderer; }
private:
    SquircleRenderer *m_renderer;
};

void VulkanSquircle::releaseResources()
{
    window()->scheduleRenderJob(new CleanupJob(m_renderer), QQuickWindow::BeforeSynchronizingStage);
    m_renderer = nullptr;
}

Platform notes

The example runs only on platforms where Qt is built with Vulkan support. To compile the example, you need a Vulkan SDK. See Vulkan Integration for information on what to install.

The example requires the Vulkan backend of the scene graph. The main.cpp file selects the backend before it creates the window:

    QQuickWindow::setGraphicsApi(QSGRendererInterface::Vulkan);

The example loads prebuilt SPIR-V shaders, squircle.vert.spv and squircle.frag.spv, from the Qt resource system.

The following examples render the same content with other graphics APIs:

Example project @ code.qt.io

See also Qt Quick Scene Graph, QQuickWindow, and QSGRendererInterface.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.