Vulkan 三角形示例
演示了使用QVulkanWindow 和Vulkan API进行渲染的基础知识。
“Hello Vulkan 三角形示例”构建了一个完整的图形处理管道(包括顶点着色器和片段着色器),用于渲染一个三角形。

启动
每个使用 Vulkan 的 Qt 应用程序都必须有一个 `Vulkan instance `,它封装了应用程序级别的状态并初始化 Vulkan 库。
QVulkanWindow 必须始终与QVulkanInstance 相关联,因此本示例在创建窗口之前先创建了该实例。QVulkanInstance 对象的存活时间也必须长于窗口。
QVulkanInstance inst;
inst.setLayers({"VK_LAYER_KHRONOS_validation"});
if(!inst.create())
qFatal("Failed to create Vulkan instance: %d", inst.errorCode());该示例会在支持的情况下启用验证层。如果请求中不包含所需的层,则该请求将被忽略。可以采用类似的方式启用其他层和扩展。
VulkanWindow w;
w.setVulkanInstance(&inst);
w.resize(1024, 768);
w.show();一旦实例准备就绪,就可以创建窗口了。请注意,w 位于栈中,且在inst 之后声明。
QVulkanWindow 的子类
要为QVulkanWindow 添加自定义功能,需通过子类化实现。这遵循了QOpenGLWindow 和QOpenGLWidget 中的现有模式。不过,QVulkanWindow 使用了一个独立的QVulkanWindowRenderer 对象。
QVulkanWindow 子类重新实现了工厂函数QVulkanWindow::createRenderer()。该函数仅返回QVulkanWindowRenderer 子类的一个新实例。为了能够通过窗口对象访问各种Vulkan资源,会将窗口的指针作为参数传递,并通过构造函数进行存储。
class VulkanWindow : public QVulkanWindow
{
public:
QVulkanWindowRenderer *createRenderer() override;
};实际渲染
QVulkanWindow 子类会在其重写的QVulkanWindowRenderer::startNextFrame() 方法中将绘制调用加入队列。完成后,它们必须回调QVulkanWindow::frameReady()。由于该示例不包含异步命令生成,因此 frameReady() 调用直接由 startNextFrame() 发起。为了获得连续更新,该示例仅需调用QWindow::requestUpdate() 来安排重绘。
该示例还演示了多采样抗锯齿。根据QVulkanWindow::supportedSampleCounts()报告的支持采样数,示例会在8x、4x或不进行多采样之间进行选择。 一旦通过 QVulkanWindow::setSamples() 完成配置,QVulkanWindow 便会处理后续工作:额外的多采样颜色缓冲区会自动创建,并且在每帧的默认渲染阶段结束时,会将数据解析到交换链缓冲区中。
运行示例
您可以通过以下方式运行该示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建与运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
© 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.