Wrapped GtkLabel huge height

Viewed 391
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?

A huge window

2 Answers

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.

Related