Gtk4 library button is not a square when defined as one

using gtk4 gui library I have this code:

use gtk4 as gtk;
use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow, Button, Box, Fixed};

fn main() -> glib::ExitCode
{
    let app = Application::builder()
    .application_id("app")
    .build();



    app.connect_activate(|app|
    {

        // We create the main window.
        let window = ApplicationWindow::builder()
        .application(app)
        .default_width(1920/2)
        .default_height(720)
        .title("Hello, World!")
        .build();


        // Create a vertical box container.
        let vbox = Fixed::new();
        
        // Create a button with text.
        let button = Button::with_label("+"); // Text on the button

        const BUTTON_SIZE: i32 = 20;
        button.set_size_request(BUTTON_SIZE, BUTTON_SIZE);

        // Connect the button's clicked signal to a callback function.
        button.connect_clicked(|_|
        {
            on_button_click();
        });

        vbox.put(&button, 10.0, 10.0);

        // Add the button to the window.
        window.set_child(Some(&vbox));
        // Show the window.
        window.present();
    });

    app.run()
}

fn on_button_click()
{

}

As you can see in these two lines:

        const BUTTON_SIZE: i32 = 20;
        button.set_size_request(BUTTON_SIZE, BUTTON_SIZE);

The button size should be 20 by 20 which is a square, however this is how it looks like when running:

Any idea why this is happening and how to fix this?

According to the GTK developers, setting fixed sizes is not supported: How to build fixed size windows in gtk 4 - #10 by ebassi - Desktop - GNOME Discourse

1 Like

then why even have this function button.set_size_request(BUTTON_SIZE, BUTTON_SIZE);?

Did you read the docs? It sets the minimum size. The widget can still grow beyond the requested size.

Indeed, size request is the minimum size that a widget will request; it will still grow larger if either its contents require that, or simply if its parent container chooses to allocate more space to it.

In general, using fixed sizes and coordinates is a very wrong way to approach laying out widgets in GTK. You're supposed to let widgets size themselves in the natural way, and use containers such as Gtk.Box to position widgets relative to each other.

What are you actually trying to do? Certainly your app doesn't just have a single button, precisely 20×20 in size, positioned precisely at (10, 10)?

1 Like

I am just starting out so yeah I was using fixed position for now but eventually use dynamic ways of doing things. thanks though.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.