Scene Graph - RHI Under QML
Shows how to render directly with QRhi under a Qt Quick scene.
The RHI Under QML example draws custom QRhi content under a Qt Quick scene. QRhi is the rendering interface that Qt Quick itself uses, so the example works with every graphics API that QRhi supports: OpenGL, Vulkan, Metal, Direct3D 11, and Direct3D 12. A custom QQuickItem creates a renderer and connects the renderer to the QQuickWindow::beforeRendering() and QQuickWindow::beforeRenderPassRecording() signals. The renderer prepares its resources in response to the first signal and records a draw call in response to the second signal. The scene graph then draws the Qt Quick items on top of the squircle. A QML animation changes the t property of the item, and the renderer passes the value to the fragment shader in a uniform buffer. Read this example to learn how to add portable custom rendering under or over a Qt Quick scene.
An underlay or overlay is one of three ways to add custom rendering to a Qt Quick scene. A QSGRenderNode renders inline with the items of the scene. A texture item renders into a separate render target and shows the texture in the scene. The Scene Graph - Custom QSGRenderNode and Scene Graph - RHI Texture Item examples show these two ways.

Running the Example
You can run the example from:
- Qt Creator
Open the Welcome mode and select the example from Examples. For more information, see Qt Creator: Tutorial: Build and run.
- Qt Extension for Visual Studio Code
Run the Qt: Open Qt examples command from the Command Palette, and select the example from the list. For more information, see Qt Extension for Visual Studio Code: Tutorial: Build and run.
What to look for
Connecting to the render signals
A visual item sets the QQuickItem::ItemHasContents flag and implements QQuickItem::updatePaintNode(). The RhiSquircle item uses the render signals of the window instead. Therefore, the position and the size of the item have no effect, and the squircle fills the whole window.
When the item gets a window, it connects QQuickWindow::beforeSynchronizing() to RhiSquircle::sync() and QQuickWindow::sceneGraphInvalidated() to RhiSquircle::cleanup(). The item also sets the clear color of the window:
RhiSquircle::RhiSquircle()
{
connect(this, &QQuickItem::windowChanged, this, &RhiSquircle::handleWindowChanged);
}
void RhiSquircle::handleWindowChanged(QQuickWindow *win)
{
if (win) {
connect(win, &QQuickWindow::beforeSynchronizing, this, &RhiSquircle::sync, Qt::DirectConnection);
connect(win, &QQuickWindow::sceneGraphInvalidated, this, &RhiSquircle::cleanup, Qt::DirectConnection);
// Ensure we start with cleared to black. The squircle's blend mode relies on this.
win->setColor(Qt::black);
}
}The RhiSquircle::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 value of t and the window to the renderer:
void RhiSquircle::sync()
{
// This function is invoked on the render thread, if there is one.
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->setT(m_t);
m_renderer->setWindow(window());
}All the connections use Qt::DirectConnection, so the slots run on the render thread that emits the signals. The renderer keeps its own copy of the window pointer, because calling QQuickItem::window() from the render thread is not fully safe.
In each frame, the scene graph does these steps in this order:
- The render loop calls QRhi::beginFrame().
- The window emits QQuickWindow::beforeRendering(). The application prepares the resources for its rendering.
- The scene graph calls QRhiCommandBuffer::beginPass().
- The window emits QQuickWindow::beforeRenderPassRecording(). The application records its draw calls.
- The scene graph records the draw calls for the Qt Quick items.
To draw on top of the Qt Quick scene instead, connect to QQuickWindow::afterRenderPassRecording(). The renderer still prepares its resources in response to QQuickWindow::beforeRendering().
Preparing the resources
The SquircleRenderer::frameStart() function gets the QRhi and the QRhiSwapChain objects from the window. In the first frame, the function loads the shaders and creates the buffers, the shader resource bindings, and the graphics pipeline:
void SquircleRenderer::frameStart()
{
// This function is invoked on the render thread, if there is one.
QRhi *rhi = m_window->rhi();
if (!rhi) {
qWarning("QQuickWindow is not using QRhi for rendering");
return;
}
QRhiSwapChain *swapChain = m_window->swapChain();
if (!swapChain) {
qWarning("No QRhiSwapChain?");
return;
}
QRhiResourceUpdateBatch *resourceUpdates = rhi->nextResourceUpdateBatch();
if (!m_pipeline) {
m_vertexShader = getShader(QLatin1String(":/scenegraph/rhiunderqml/squircle_rhi.vert.qsb"));
if (!m_vertexShader.isValid())
qWarning("Failed to load vertex shader; rendering will be incorrect");
m_fragmentShader = getShader(QLatin1String(":/scenegraph/rhiunderqml/squircle_rhi.frag.qsb"));
if (!m_fragmentShader.isValid())
qWarning("Failed to load fragment shader; rendering will be incorrect");
m_vertexBuffer.reset(rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertices)));
m_vertexBuffer->create();
resourceUpdates->uploadStaticBuffer(m_vertexBuffer.get(), vertices);
const quint32 UBUF_SIZE = 4 + 4; // 2 floats
m_uniformBuffer.reset(rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, UBUF_SIZE));
m_uniformBuffer->create();
float yDir = rhi->isYUpInNDC() ? 1.0f : -1.0f;
resourceUpdates->updateDynamicBuffer(m_uniformBuffer.get(), 4, 4, &yDir);
m_srb.reset(rhi->newShaderResourceBindings());
const auto visibleToAll = QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage;
m_srb->setBindings({
QRhiShaderResourceBinding::uniformBuffer(0, visibleToAll, m_uniformBuffer.get())
});
m_srb->create();
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({
{ 2 * sizeof(float) }
});
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float2, 0 }
});
m_pipeline.reset(rhi->newGraphicsPipeline());
m_pipeline->setTopology(QRhiGraphicsPipeline::TriangleStrip);
QRhiGraphicsPipeline::TargetBlend blend;
blend.enable = true;
blend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
blend.srcAlpha = QRhiGraphicsPipeline::SrcAlpha;
blend.dstColor = QRhiGraphicsPipeline::One;
blend.dstAlpha = QRhiGraphicsPipeline::One;
m_pipeline->setTargetBlends({ blend });
m_pipeline->setShaderStages({
{ QRhiShaderStage::Vertex, m_vertexShader },
{ QRhiShaderStage::Fragment, m_fragmentShader }
});
m_pipeline->setVertexInputLayout(inputLayout);
m_pipeline->setShaderResourceBindings(m_srb.get());
m_pipeline->setRenderPassDescriptor(swapChain->currentFrameRenderTarget()->renderPassDescriptor());
m_pipeline->create();
}
float t = m_t;
resourceUpdates->updateDynamicBuffer(m_uniformBuffer.get(), 0, 4, &t);
swapChain->currentFrameCommandBuffer()->resourceUpdate(resourceUpdates);
}Notice these points in the code:
- A QRhiResourceUpdateBatch collects the buffer updates. QRhiCommandBuffer::resourceUpdate() then adds the updates to the command buffer of the current frame.
- The vertex buffer is immutable. The renderer uploads the vertices only once.
- The uniform buffer is dynamic. The renderer writes the value of
tat offset 0 in every frame. - The float value at offset 4 handles the differences between the coordinate systems of the graphics APIs. When QRhi::isYUpInNDC() returns
false, as with Vulkan, the value is -1.0, and the shader flips the Y coordinate. The output then looks the same with every graphics API. The renderer writes this value only once. Renderers that use a perspective projection can multiply the projection matrix by QRhi::clipSpaceCorrMatrix() to handle the differences. For more information, see Coordinate system differences between graphics APIs. - The graphics pipeline uses the render pass descriptor of the swap chain. The pipeline works only with the swap chain, or with a render target that has a compatible render pass descriptor.
The QQuickWindow::swapChain() function returns a swap chain only for an on-screen window. A window that uses QQuickRenderControl, for example to render into a texture, has no swap chain.
Recording the draw call
The SquircleRenderer::mainPassRecordingStart() function records a draw call for a triangle strip with four vertices:
void SquircleRenderer::mainPassRecordingStart()
{
// This function is invoked on the render thread, if there is one.
QRhi *rhi = m_window->rhi();
QRhiSwapChain *swapChain = m_window->swapChain();
if (!rhi || !swapChain)
return;
const QSize outputPixelSize = swapChain->currentFrameRenderTarget()->pixelSize();
QRhiCommandBuffer *cb = m_window->swapChain()->currentFrameCommandBuffer();
cb->setViewport({ 0.0f, 0.0f, float(outputPixelSize.width()), float(outputPixelSize.height()) });
cb->setGraphicsPipeline(m_pipeline.get());
cb->setShaderResources();
const QRhiCommandBuffer::VertexInput vbufBinding(m_vertexBuffer.get(), 0);
cb->setVertexInput(0, 1, &vbufBinding);
cb->draw(4);
}The function records its commands on the QRhiCommandBuffer of the swap chain, before the commands of the scene graph in the main render pass. The function uses QRhi commands, not native commands, so the example does not call QQuickWindow::beginExternalCommands(). The viewport size comes from QRhiRenderTarget::pixelSize(), which already includes the device pixel ratio. The example records one draw call, but a renderer can also create several graphics pipelines and record several draw calls.
The graphics pipeline blends the squircle colors additively with the colors in the render target. The scene graph clears the render target 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.
Note: If your rendering writes to the depth buffer, the depth values can affect the Qt Quick content. For more information, see Qt Quick Scene Graph Default Renderer.
Releasing the resources
The renderer owns the QRhi 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
RhiSquircle::cleanup(). - When the item leaves the window, the scene graph calls QQuickItem::releaseResources(). The
RhiSquircle::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 RhiSquircle::cleanup()
{
// This function is invoked on the render thread, if there is one.
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 RhiSquircle::releaseResources()
{
window()->scheduleRenderJob(new CleanupJob(m_renderer), QQuickWindow::BeforeSynchronizingStage);
m_renderer = nullptr;
}Platform notes
The main.cpp file does not select a graphics API, so Qt Quick uses the default graphics API of the platform. With the software adaptation of Qt Quick, the example prints a warning and draws only the Qt Quick items.
QRhi has limited compatibility guarantees. To use the QRhi APIs, the example links to Qt::GuiPrivate and includes <rhi/qrhi.h>.
The vertex and fragment shaders are Vulkan-compatible GLSL. The qt_add_shaders command in CMakeLists.txt compiles the shaders to SPIR-V at build time and translates them to the shading languages of the other graphics APIs, such as HLSL and MSL. Because of this, one set of shaders works with every graphics API. The command adds the resulting .qsb files to the resources. The BASE argument removes the ../shared prefix, and the PREFIX argument adds /scenegraph/rhiunderqml. The resulting path is :/scenegraph/rhiunderqml/squircle_rhi.vert.qsb.
qt_add_shaders(rhiunderqml "rhiunderqml_shaders"
PRECOMPILE
OPTIMIZED
PREFIX
/scenegraph/rhiunderqml
BASE
../shared
FILES
../shared/squircle_rhi.vert
../shared/squircle_rhi.frag
)For qmake, the example includes prebuilt .qsb files in the prebuilts_for_qmake directory and lists the files in the .qrc file. Applications that use CMake generate the .qsb files at build time with qt_add_shaders.
The following examples render the same content with a native graphics API:
- Direct3D 11 Under QML uses Direct3D 11.
- OpenGL Under QML uses OpenGL.
- Metal Under QML uses Metal.
- Vulkan Under QML uses Vulkan.
See also Qt Quick Scene Graph, Scene Graph - RHI Texture Item, and Scene Graph - Custom QSGRenderNode.
© 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.