本页内容

简易 QML

Minimal QML 是一个简单的示例,演示了如何使用 QML 编写 Wayland 合成器。

“简易 QML”是一个桌面风格的 Wayland 合成器示例,旨在以尽可能少的代码实现完整的Qt Wayland Compositor 。该合成器采用Qt Quick 和 QML 实现。

带客户端窗口的简易 QML 合成器

WaylandCompositor 对象

合成器的顶级项是WaylandCompositor 。它代表 Wayland 服务器本身,并管理传入客户端的连接。

默认情况下,服务器支持用于与客户端通信的核心 Wayland 协议。不过,通常您还会希望支持该协议的一个或多个扩展。这为客户端提供了更多工具,使其能够更灵活地发挥其在窗口系统中的作用。

Qt 支持多种标准和常见的扩展。此外,只要在客户端和服务器端代码中都能添加支持,创建和支持自定义扩展也非常简单。

Shell 扩展

通常,合成器至少会支持一种Shell 扩展。通过将扩展实例化为 `WaylandCompositor ` 对象的直接子节点,即可将其添加到合成器中。这些扩展会自动添加到其 `extensions ` 属性中,并在客户端连接时广播给客户端。

WlShell {
    onWlShellSurfaceCreated: (shellSurface) => shellSurfaces.append({shellSurface: shellSurface});
}
XdgShell {
    onToplevelCreated: (toplevel, xdgSurface) => shellSurfaces.append({shellSurface: xdgSurface});
}
IviApplication {
    onIviSurfaceCreated: (iviSurface) => shellSurfaces.append({shellSurface: iviSurface});
}

“Minimal QML”示例支持三种不同的 Shell:WlShell 、XdgShell 和IviApplication 。

客户端可以连接到其中任意一个,该连接将作为客户端与合成器之间进行特定通信的通道,例如创建新窗口、协商大小等。

当客户端创建一个新表面时,其活动扩展将收到一个相关信号。该信号包含一个ShellSurface 参数。根据接收信号的扩展不同,该参数将分别是ShellSurface 的子类:WlShellSurface 、XdgSurface 或IviSurface 。

ShellSurface 可用于访问特定界面的 Shell 扩展功能。在“Minimal QML”示例中,我们仅需将客户端添加到场景中。为记录新窗口的存在,我们将它添加到一个简单的 `ListModel ` 中以备保存。

ListModel { id: shellSurfaces }

创建场景

大部分必要的合成器代码已经准备就绪。最后一步是确保应用程序确实能在屏幕上显示出来。

对于所有合成器,我们都必须定义至少一个输出。这可以通过实例化一个WaylandOutput 对象并将其作为WaylandCompositor 的直接子节点来实现。如果只有一个输出,它将代表系统上的主屏幕。 (如果系统支持多屏幕,您还可以创建多个WaylandOutput 对象来处理多个屏幕。有关此内容的更多详细信息,请参阅“多屏幕”示例。)

WaylandOutput {
    sizeFollowsWindow: true
    window: Window {
        width: 1024
        height: 768
        visible: true

在WaylandOutput 内部,我们创建一个Window对象,用作场景的容器。在示例中,我们为该对象指定了尺寸。当合成器作为应用程序在支持自定义窗口尺寸的另一个窗口系统中运行时,将使用该尺寸。 在嵌入式设备上的典型用例中,当合成器是唯一运行的显示服务器时,它很可能运行在全屏平台插件(如eglfs )上,此时此处设置的大小将无关紧要。

最后一步是为已创建的每个 `ShellSurface ` 对象创建相应项。为此,我们可以使用 `ShellSurfaceItem ` 类。

Repeater {
    model: shellSurfaces
    // ShellSurfaceItem handles displaying a shell surface.
    // It has implementations for things like interactive
    // resize/move, and forwarding of mouse and keyboard
    // events to the client process.
    ShellSurfaceItem {
        shellSurface: modelData
        onSurfaceDestroyed: shellSurfaces.remove(index)
    }
}

我们为模型中的每个 shell 表面创建一个ShellSurfaceItem ,并将它们赋值给shellSurface 属性。此外,我们确保在 shell 表面被销毁时更新模型。这种情况可能发生在客户端手动关闭窗口时,或者程序退出或崩溃时。

以上就是使用Qt Quick 和QML创建一个可运行的Wayland合成器所需的全部代码。若想查看另一个用QML编写且功能更丰富的合成器示例,请参阅Fancy Compositor示例。

示例项目 @ code.qt.io

© 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.