Scene Graph - Metal Under QML
Shows how to render directly with Metal under a Qt Quick scene.
The Metal Under QML example draws custom Metal content under a Qt Quick scene. A custom QQuickItem creates a renderer. The renderer gets the Metal device and the render command encoder 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 Metal rendering with Qt Quick.

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
The MetalSquircle::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 MetalSquircle::sync()
{
if (!m_renderer) {
m_renderer = new SquircleRenderer;
// Initializing resources is done before starting to encode render
// commands, 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());
}Both connections use Qt::DirectConnection, so the slots run on the render thread that emits the signals.
Getting the Metal device
The scene graph emits QQuickWindow::beforeRendering() at the start of each frame, before the main render pass starts. In response, the renderer queries the Metal device that the scene graph uses:
void SquircleRenderer::frameStart()
{
QSGRendererInterface *rif = m_window->rendererInterface();
// We are not prepared for anything other than running with the RHI and its Metal backend.
Q_ASSERT(rif->graphicsApi() == QSGRendererInterface::Metal);
m_device = (id<MTLDevice>) rif->getResource(m_window, QSGRendererInterface::DeviceResource);
Q_ASSERT(m_device);
if (m_vert.isEmpty())
prepareShader(VertexStage);
if (m_frag.isEmpty())
prepareShader(FragmentStage);
if (!m_initialized)
init(m_window->graphicsStateInfo().framesInFlight);
}On the first frame, the renderer creates its resources on the device of the scene graph, so the resources work in the render pass of the scene graph. The resources include one uniform buffer for each frame in flight. QQuickWindow::graphicsStateInfo() reports the number of frames in flight.
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. The render command encoder exists only after the main render pass starts, so the example needs this second signal. In response, the renderer gets the MTLRenderCommandEncoder of the main render pass and records the draw commands with this encoder:
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();
id<MTLRenderCommandEncoder> encoder = (id<MTLRenderCommandEncoder>) rif->getResource(
m_window, QSGRendererInterface::CommandEncoderResource);
Q_ASSERT(encoder);
m_window->beginExternalCommands();
void *p = [m_ubuf[stateInfo.currentFrameSlot] contents];
float t = m_t;
memcpy(p, &t, 4);
MTLViewport vp;
vp.originX = 0;
vp.originY = 0;
vp.width = m_viewportSize.width();
vp.height = m_viewportSize.height();
vp.znear = 0;
vp.zfar = 1;
[encoder setViewport: vp];
[encoder setFragmentBuffer: m_ubuf[stateInfo.currentFrameSlot] offset: 0 atIndex: 0];
[encoder setVertexBuffer: m_vbuf offset: 0 atIndex: 1];
[encoder setRenderPipelineState: m_pipeline];
[encoder drawPrimitives: MTLPrimitiveTypeTriangleStrip vertexStart: 0 vertexCount: 4 instanceCount: 1 baseInstance: 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. To draw on top of the Qt Quick scene instead, connect to QQuickWindow::afterRenderPassRecording().
Animating the shader input
The MetalSquircle.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 current frame slot. The fragment shader reads this buffer:
import QtQuick
import MetalUnderQML
Item {
width: 320
height: 480
MetalSquircle {
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 Metal 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
MetalSquircle::cleanup(). - When the item leaves the window, the scene graph calls QQuickItem::releaseResources(). The
MetalSquircle::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 MetalSquircle::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 MetalSquircle::releaseResources()
{
window()->scheduleRenderJob(new CleanupJob(m_renderer), QQuickWindow::BeforeSynchronizingStage);
m_renderer = nullptr;
}Platform notes
The example runs on macOS and iOS only. The example requires the Metal backend of the scene graph. The main.cpp file selects the backend before it creates the window:
QQuickWindow::setGraphicsApi(QSGRendererInterface::Metal);The example compiles the Metal shaders from source at runtime with the newLibraryWithSource method of MTLDevice.
The following examples render the same content with other graphics APIs:
- Direct3D 11 Under QML uses Direct3D 11.
- OpenGL Under QML uses OpenGL.
- Vulkan Under QML uses Vulkan.
- RHI Under QML uses QRhi, so it works with Direct3D, Metal, OpenGL, and Vulkan.
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.