How to set fixed width and height for `Gtk.Box`?

I have a widget with image and texts below it. But when the text is too long, the widget resizes, which is breaking app’s logic. Is there any way to set widget’s width (and height?) fixed?

Запись экрана от 2024-11-06 19-43-34

Blueprint code of the widget:

using Gtk 4.0;

template $songCard: Box {
  orientation: vertical;
  height-request: 160;
  width-request: 160;
  valign: center;
  halign: center;
  hexpand: false;
  vexpand: false;

  styles [
    "card",
  ]

  Overlay {
    Picture cover {
      name: 'cover';
      file: "file:/home/dzheremi/Pictures/note.png";
    }

    [overlay]
    Box hover {
      name: 'hover';
      orientation: vertical;
      homogeneous: true;
      hexpand: true;
      vexpand: true;

      Image play {
        name: 'play';
        icon-name: 'media-playback-start-symbolic';
        pixel-size: 45;
      }
    }
  }

  Box {
    orientation: horizontal;
    halign: start;
    margin-top: 4;
    margin-start: 8;
    margin-bottom: 1;
    margin-end: 8;
    hexpand: false;
    vexpand: false;

    Label song_title {
      label: "Unknowns";

      styles [
        'heading',
      ]
    }
  }

  Box {
    orientation: horizontal;
    halign: start;
    margin-top: 1;
    margin-start: 8;
    margin-bottom: 4;
    hexpand: false;
    vexpand: false;

    Label song_artist {
      label: "Unknown";
    }
  }
}

Can’t you ellipsize the label ?

1 Like

Hi,

GtkLabel will automatically expand to ensure all the text is visible.
There are some properties to control how much it can expand:

Alternatively, if your text area is constrained with a fixed size, consider using a Gtk.Inscription instead of a GtkLabel, which is exactly designed for this usecase.

No, the GtkBox will grow accordingly to its children size request.
Instead, you have to prevent the Box children to request too much size, as I described above.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.