Reputation: 6210
auto widget=gtk_label_new(text);
m_handle=GTK_LABEL(widget);
gtk_label_set_line_wrap(m_handle,TRUE);
gtk_label_set_max_width_chars(m_handle,80);
gtk_widget_set_size_request(GTK_WIDGET(m_handle),-1,1);
And, the label wraps but GTK thinks the widget require the height equal to line break after every word. And no, I cannot shrink the window manually. How to restore its height?
Upvotes: 4
Views: 560
Reputation: 101
Best working solution for me so far (gtkmm):
class MultiLineLabel : public Gtk::Label {
public:
MultiLineLabel() : Gtk::Label() {
#if GTKMM_MAJOR_VERSION >= 3
set_line_wrap();
#endif
}
void set_markup(const Glib::ustring& s) {
Gtk::Label::set_markup(s);
m_markup = s;
}
void get_preferred_height_for_width_vfunc(int width, int& minimum_height, int& natural_height) const {
Gtk::Label::get_preferred_height_for_width_vfunc(width, minimum_height, natural_height);
Pango::Layout* origLayout = const_cast<Pango::Layout*>(get_layout().operator->());
Glib::RefPtr<Pango::Layout> layout = origLayout->copy();
Glib::ustring s = (!m_markup.empty()) ? m_markup : get_text();
layout->set_markup(s);
int w, h;
layout->get_pixel_size(w, h);
h += get_margin_top() + get_margin_bottom();
minimum_height = h;
if (natural_height < h)
natural_height = h;
}
private:
Glib::ustring m_markup;
};
This solution overrides get_preferred_height_for_width_vfunc()
and uses the label's current layout settings and current text (or markup) to calculate the exact width and height for that text required for rendering it on screen.
Other suggestions I found on the net so far, did not work for me. For instance the gtk docs suggest using gtk_label_set_width_chars(GTK_LABEL(label), 30)
, but that just reduces the wasted height a bit, it does not fix the problem. So if the text goes over more than couple lines, you will still have plenty of vertical space wasted when using gtk_label_set_width_chars(GTK_LABEL(label), 30)
. Calling gtk_window_set_default_size(GTK_WINDOW(win), x, -1);
did not make any difference to me.
Upvotes: 1
Reputation: 1493
Although I'm not at all experienced with Gtk3 programming, I have seen a very similar phenomenon in Qt5.
I think what happens is that Gtk3 will set the minimum height of the label to the height it would have when wrapped to its minimum width. I mean the minimum width of the label itself, so even if the window cannot be made smaller, the label could potentially, if there were some other widgets next to it in the window.
This mechanism is described here: https://developer.gnome.org/gtk3/stable/GtkWidget.html#geometry-management
Note especially:
The minimum height for the minimum width is normally used to set the minimum size constraint on the toplevel (unless gtk_window_set_geometry_hints() is explicitly used instead).
So you could try setting a bigger minimum width constraint on the label itself, and see if that changes anything.
Upvotes: 4