You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于gtk4-rs的GTK4应用如何移除默认标题栏并保留其他装饰

在GTK4 + gtk-rs中替换默认标题栏并保留窗口装饰

要移除默认标题栏但保留窗口边框和控制按钮(红绿灯),核心是利用GTK4的set_titlebar方法替换默认标题栏部件,而非通过CSS隐藏或修改窗口装饰属性。以下是具体实现步骤和代码示例:

核心思路

GTK4中,窗口的边框和控制按钮由窗口管理器提供(当decorated属性为true时默认开启),而标题栏是GTK自身的部件。通过set_titlebar方法将自定义部件设为窗口标题栏,即可替换默认样式,同时保留窗口管理器提供的边框和控制按钮。

实现代码

use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Box, Orientation, Label, Button, EventControllerMotion, DragButton};

fn main() {
    let app = Application::builder()
        .application_id("com.example.CustomTitlebarDemo")
        .build();

    app.connect_activate(|app| {
        // 创建主窗口,保持默认decorated=true以保留边框和控制按钮
        let window = ApplicationWindow::builder()
            .application(app)
            .default_width(600)
            .default_height(400)
            .build();

        // 创建自定义标题栏容器(用水平Box示例,可替换为任意GTK部件)
        let custom_titlebar = Box::builder()
            .orientation(Orientation::Horizontal)
            .spacing(8)
            .margin_start(12)
            .margin_end(12)
            .margin_top(8)
            .margin_bottom(8)
            .build();

        // 添加自定义标题内容
        let title_label = Label::builder()
            .label("我的自定义标题")
            .hexpand(true)
            .halign(gtk::Align::Center)
            .build();
        custom_titlebar.append(&title_label);

        // 添加自定义功能按钮
        let settings_btn = Button::builder()
            .label("设置")
            .build();
        custom_titlebar.append(&settings_btn);

        // 给自定义标题栏添加窗口拖动功能(默认标题栏自带此功能,自定义需手动实现)
        let drag_controller = EventControllerMotion::new();
        drag_controller.connect_press(move |_, x, y| {
            window.begin_move_drag(DragButton::Primary, x as i32, y as i32, gtk::current_event_time());
            gtk::Inhibit(false)
        });
        custom_titlebar.add_controller(drag_controller);

        // 替换默认标题栏为自定义部件
        window.set_titlebar(Some(&custom_titlebar));

        window.show();
    });

    app.run();
}

关键说明

  1. 保留窗口装饰:无需修改decorated属性(默认值为true),窗口管理器会自动提供边框和控制按钮。
  2. 自定义标题栏灵活性:可以用任何GTK部件作为标题栏,比如GtkHeaderBar(如果需要部分默认功能)或自定义容器,完全按需设计样式和功能。
  3. 拖动功能:自定义标题栏不会自动支持窗口拖动,需通过EventControllerMotion监听点击事件并调用begin_move_drag实现。

内容的提问来源于stack exchange,提问作者DischordDynne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:35:27