For most of Qt’s history, custom graphics in a Qt application meant using OpenGL. You needed QGLWidget, later QOpenGLWidget, or some raw GL calls from inside a QQuickFramebufferObject. That held up while OpenGL ran everywhere. Then Apple deprecated it in macOS 10.14, Windows drivers kept putting Direct3D first, and Vulkan became the API to target on Linux and Android. A toolkit that wants to run well cross-platform can’t sit on GL alone anymore.
Qt’s response is QRhi, the Qt Rendering Hardware Interface. It shipped as a technology preview behind Qt Quick in Qt 5.14 and became the foundation of Qt Quick’s renderer in Qt 6. QRhi lets most of your rendering code stop caring which backend is underneath. The code below assumes Qt 6.6 or later, the first release where the QRhi headers can be included from application code.
What QRhi abstracts and what it leaves to you
QRhi is an abstraction over OpenGL, OpenGL ES, Vulkan, Metal, Direct3D 11 and Direct3D 12. Each QRhi instance is backed by one of those and is picked at runtime by whoever calls QRhi::create(). There’s also a Null implementation that issues no graphics calls at all, which comes in handy for tests and headless tooling.
If you’ve written Vulkan, Metal or D3D12 code, the vocabulary will look familiar: buffers, textures, samplers, render targets, shader resource bindings, pipelines and command buffers. The model is much closer to those APIs than to OpenGL. Blend, depth and rasterizer state are baked into an immutable QRhiGraphicsPipeline, and each frame’s work is recorded into a QRhiCommandBuffer. On the OpenGL and D3D11 backends, Qt records the commands itself and replays them as immediate-mode calls when the frame is submitted.
Recording a frame
Once the buffers, the shader resource bindings and the pipeline exist, a frame rendered to a window looks like this:
if (rhi->beginFrame(swapChain) != QRhi::FrameOpSuccess)
return; // out-of-date swapchain or lost device, handle and retry
QRhiCommandBuffer *cb = swapChain->currentFrameCommandBuffer();
const QSize size = swapChain->currentPixelSize();
QMatrix4x4 mvp = rhi->clipSpaceCorrMatrix();
mvp.perspective(45.0f, size.width() / float(size.height()), 0.01f, 100.0f);
mvp *= modelView;
QRhiResourceUpdateBatch *updates = rhi->nextResourceUpdateBatch();
updates->updateDynamicBuffer(uniformBuffer, 0, 64, mvp.constData());
cb->beginPass(swapChain->currentFrameRenderTarget(), Qt::black, { 1.0f, 0 }, updates);
cb->setGraphicsPipeline(pipeline);
cb->setViewport(QRhiViewport{ 0, 0, float(size.width()), float(size.height()) });
cb->setShaderResources();
const QRhiCommandBuffer::VertexInput vertexBinding(vertexBuffer, 0);
cb->setVertexInput(0, 1, &vertexBinding);
cb->draw(3);
cb->endPass();
rhi->endFrame(swapChain);A few things are worth calling out:
clipSpaceCorrMatrix()hides the clip-space differences between APIs. Vulkan’s Y axis points down, and every backend except OpenGL expects depth in [0, 1] rather than [-1, 1]. Pre-multiplying with this matrix lets you keep using GL-style projections fromQMatrix4x4::perspective()on every backend.64, mvp.constData()rather thansizeof(mvp), &mvp. In Qt 6,QMatrix4x4stores an extra flags field next to its 16 floats, sosizeofgives you 68 bytes and the copy would spill past the matrix into whatever follows it in the uniform buffer. This is an easy mistake to make, and Qt’s own examples use the explicit 64.- The update batch goes into
beginPass(), so the upload is committed before the pass starts. QRhi tracks resource usage and inserts the barriers and layout transitions that Vulkan and D3D12 need, which is a big part of what you’d otherwise have to write by hand. setViewport()isn’t part of the pipeline state, so set it in every pass after binding the pipeline.setShaderResources()with no arguments binds theQRhiShaderResourceBindingsthe pipeline was created with.
What’s left out is the setup: creating the QRhi, the swapchain and its render pass descriptor, the pipeline, and handling resizes. The RHI Window Example covers all of that in a few hundred lines.
Picking a backend and checking what it supports
Each backend has its own floor, and creation fails on hardware that can’t meet it:
| Backend | Minimum | Platforms |
|---|---|---|
| OpenGL | OpenGL 2.1 or OpenGL ES 2.0 | Most |
| Vulkan | Vulkan 1.0 | Windows, Linux, Android (macOS and iOS through MoltenVK) |
| Metal | Metal 1.2 | macOS, iOS |
| Direct3D 11 | D3D 11.2, Shader Model 5.0 | Windows |
| Direct3D 12 | Windows 10 1703, Shader Model 5.0 (Qt 6.6+) | Windows |
Qt Quick chooses for you unless told otherwise: Direct3D 11 on Windows, Metal on Apple platforms, and OpenGL everywhere else, including desktop Linux. Vulkan is opt-in. You can set QSG_RHI_BACKEND=vulkan in the environment, or ask for it in code before the first window exists:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickWindow::setGraphicsApi(QSGRendererInterface::Vulkan);
QQmlApplicationEngine engine;
engine.loadFromModule("MyApp", "Main");
return app.exec();
}The call has to come before any QQuickWindow is created, because the window’s QRhi is set up when it’s first exposed. The environment variable is handy for testing a build against a different backend without recompiling.
A floor as low as OpenGL 2.1 means optional features really are optional. Compute shaders, multisample textures, geometry shaders and wide lines all depend on the backend and the driver, so query them before you rely on them:
if (rhi->isFeatureSupported(QRhi::Compute)) {
// GPU particle simulation
} else {
// CPU fallback
}
const int maxTextureSize = rhi->resourceLimit(QRhi::TextureSizeMax);On Vulkan, Metal or D3D, QRhi::Compute is basically always there. On OpenGL it needs GL 4.3 or ES 3.1. That’s the case you’ll actually hit in the field, usually on older Linux machines or embedded boards that end up on the default GL backend.
Note: Portable here means one Qt rendering interface across several backends. It doesn’t mean every backend supports every feature, or that you’ll never need a native API.
When you do need the native API (to share a texture with a video decoder or another engine, say), QRhi gives you a way down. QRhi::nativeHandles() exposes the device and queue, QRhiTexture::nativeTexture() gives you the underlying VkImage, MTLTexture or ID3D11Texture2D, and QRhiTexture::createFrom() wraps an existing native texture. Any code that goes through those is tied to that backend, so keep it small and behind a switch on rhi->backend().
Writing shaders once with Qt Shader Tools
Shaders are where QRhi differs most from Qt 5. QRhi consumes QShader objects. It doesn’t compile shader source, and the GLSL you wrote for Qt 5 won’t work as-is.
You write shaders once in Vulkan-flavoured GLSL. Qt Shader Tools compiles that to SPIR-V with glslang, uses SPIRV-Cross to reflect it and translate it into GLSL (several versions), HLSL and MSL, then packs the lot into a .qsb file. At runtime QRhi loads the QShader and picks the variant that matches its backend. Here’s a greyscale fragment shader for a Qt Quick ShaderEffect:
#version 440
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
float qt_Opacity;
float strength;
};
layout(binding = 1) uniform sampler2D source;
void main()
{
vec4 c = texture(source, qt_TexCoord0);
float grey = dot(c.rgb, vec3(0.299, 0.587, 0.114));
fragColor = mix(c, vec4(vec3(grey), c.a), strength) * qt_Opacity;
}Coming from Qt 5’s OpenGL-style GLSL, the differences are mechanical but unavoidable. You need #version 440, explicit location and binding qualifiers, and a single std140 uniform block instead of loose uniform declarations. For a ShaderEffect that only supplies a fragment shader, qt_Matrix and qt_Opacity must open the block because Qt’s default vertex shader expects them there. The remaining members map to QML properties by name, so strength here is a property real strength on the item.
You don’t run the compiler by hand. Qt’s CMake integration processes the shaders at build time and puts the results in the resource system:
qt_add_shaders(app "effects"
PREFIX "/"
FILES
shaders/greyscale.frag
)That produces :/shaders/greyscale.frag.qsb, which the ShaderEffect references as fragmentShader: "qrc:/shaders/greyscale.frag.qsb". Custom scene graph materials work the same way through QSGMaterialShader::setShaderFileName().
By default the HLSL and MSL variants in a
.qsbare stored as source, so Direct3D and Metal still compile them when the pipeline is created. PassingPRECOMPILEtoqt_add_shaders()runsfxcat build time and stores DXBC instead, but only when building on Windows. Qt Quick 3D is the exception to the whole build-time model. It generates material shaders at runtime and links Qt Shader Tools to do so.
How Qt Quick and widgets sit on top of QRhi
In Qt 6, Qt Quick’s scene graph renders through QRhi whenever it’s hardware accelerated. The software adaptation still exists for machines without a usable GPU, but there’s no longer a separate direct-OpenGL renderer. Laszlo Agocs’ Graphics in Qt 6.0 post walks through that transition in detail.
If your application is plain QML, none of this affects you. The work shows up where Qt 5 code reached for OpenGL directly:
QQuickFramebufferObjectstill compiles, but it only works when Qt Quick is running on OpenGL, so you’d have to force that backend. Its portable replacement isQQuickRhiItem(Qt 6.7).QOpenGLWidgethas the same story on the widgets side.QRhiWidget(Qt 6.7) is the portable equivalent.QSGTexture::textureId()is gone. Native texture handles now come throughQSGTexture::nativeInterface(), which is backend-specific by design.- Custom GL in
beforeRenderinghas to be wrapped inQQuickWindow::beginExternalCommands()andendExternalCommands(), and it only makes sense on the OpenGL backend. ShaderEffectand custom materials need.qsbfiles, as described above.
The same layering goes the other way too. QQuickRenderControl, QQuickRenderTarget and QQuickGraphicsDevice let Qt Quick render into a texture you own, on a device you created. That’s how you embed a QML UI in a game engine, render offscreen, or drive an XR headset (Qt Quick 3D XR builds on it). Qt won’t reconcile device ownership, resource lifetimes or synchronization with the other renderer for you, though. You still have to get those right yourself.
The cost of calling QRhi directly
Qt Quick, ShaderEffect and the widget classes are ordinary public API. QRhi itself isn’t quite. The QRhi classes, along with QShader and QShaderDescription, carry an explicit warning in the docs: no source or binary compatibility guarantees. Source-incompatible changes are kept to a minimum and only land in minor releases (6.7, 6.8 and so on), but they do land. To use them, you link against the private Gui target and include the rhi/ headers:
target_link_libraries(app PRIVATE Qt6::GuiPrivate)#include <rhi/qrhi.h>Before 6.6 the same classes lived in private qrhi_p.h headers with no guarantees at all, so 6.6 counts as an improvement. In practice it means you pin the Qt minor version you build against and expect small fixups on upgrades. QQuickRhiItem and QRhiWidget are fully public classes, but the code inside your subclass talks to QRhi, so the same contract applies.
If what you need is portable 2D or 3D content in Qt Quick, stay with ShaderEffect, custom materials or Qt Quick 3D and let the scene graph own the QRhi. Go direct only when you need control over the frame that those layers don’t give you.
Conclusion
QRhi gives Qt one rendering model across OpenGL, Vulkan, Metal and both Direct3D versions, and Qt Shader Tools moves shader translation out of the runtime and into the build. Qt Quick, Qt Quick 3D, and now widgets through QRhiWidget, all sit on top of it. Optional features vary wildly between a GL 2.1 driver and a D3D12 one, native interop is backend-specific, and the API itself comes with a compatibility warning.
Having said that, the alternative was a toolkit tied to an API that one major platform has deprecated and others treat as legacy. With QRhi, the common rendering work stays in one interface, and the places where you depend on a particular backend are visible in the code instead of spread across it.