Rotate a Label in Gtk4

Gtk3 had GtkLabel.set_angle which was removed with Gtk4.

I am aware of this response, however I do not want to have to manually render a pango layout rather than just operating on GtkLabel like before. set_angle did not need any interaction with the underlying pango layout, I want the object rendering the text to stay being a GtkLabel.

I tried the following (in C++ here, though I am using the C binding)

auto* label = GTK_LABEL(gtk_label_new("test"));
auto* layout = gtk_label_get_layout(label);
auto* context = pango_layout_get_context(layout);
auto* matrix = new PangoMatrix(PANGO_MATRIX_INIT);
pango_matrix_rotate(matrix, 90);
pango_context_set_matrix(context, matrix);
pango_layout_context_changed(layout);

Which had no effect, I assume because the labels layout is read-only.

I am also aware of GtkFixed.set_child_transform, which lets me rotate any widget, but only in a fixed context. I want the label to align normally, respecting it’s halign and valign properties. The only way to apply a transform to a widget I could find was through GtkFixed.

The Pango attributes related to gravity almost got me there, however they only rotate the letters, not the entire text:

auto* label = GTK_LABEL(gtk_label_new("<span gravity=\"east\" gravity_hint=\"strong\">test</span>");
gtk_label_use_markup(label);

Prints letter horizontally, with each letter rotate by 90°. I want the entire label to be rotated by 90° (or an arbitrary number of degrees), not just every letter.

How do I rotate a GtkLabel around it’s centroid in Gtk4? A code snippet would help a lot, thank you in advance.

If a static approach is enough for you, you can use CSS to rotate the label and let Gsk do the underlying work for you.

I think the following approach will do it: Add a style class to the StyleContext of the label by calling get_style_context and gtk_style_context_add_class and then provide the style with gtk_style_context_add_provider.

If you choserotated as style class name the appropriate css string to rotate the label would be

label.rotated { 	transform: rotate(90deg); }

It is easy to test the effects of the transformation without editing code by invoking the GTK Inspector. See the following picture

You can also use gtk_snapshot_rotate in the snapshot function of the parent widget if you need more control than what CSS gives you. Note the transform should also be rotated when calling gtk_widget_allocate if you want the input coordinates to be correct.

And you’ll need to change the measure() function as well, to provide the correctly transformed width and height.

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