c++gtkgtkmmpango

Change font of Gtk::Label


Using gtkmm 3.0 with c++, in a Gtk::Window, I have a Gtk::Label named "bezeichnung" showing text.

How can I change the font of this label?

There seems to be no function to set the font for a Gtk::Label. To deal with functions of the general Gtk::Widget from which Gtk::Label derives is difficult to understand, since it uses Pango. This is my code so far:

Pango::FontDescription font;
font.set_family("Monospace");
font.set_weight(Pango::WEIGHT_ULTRABOLD);
font.set_size(14 * PANGO_SCALE);

bezeichnung = Gtk::Label("leer");
bezeichnung.set_halign(Gtk::ALIGN_CENTER);
auto context = bezeichnung.create_pango_context();
context->set_font_description(font);

The font does not change. How can I set the changed Pango context back to the label?


Solution

  • Here is a solution, close to yours, that works for me on Ubuntu with Gtkmm 3.24.20:

    #include <gtkmm.h>
    
    class MainWindow : public Gtk::ApplicationWindow
    {
    
    public:
    
        MainWindow();
    
    private:
    
        Gtk::Label m_label{"leer"};
    
    };
    
    MainWindow::MainWindow()
    {
        auto context = m_label.get_pango_context();  
        auto font = context->get_font_description();
        font.set_family("Monospace");
        font.set_weight(Pango::WEIGHT_ULTRABOLD);
        font.set_size(14 * PANGO_SCALE);  
        context->set_font_description(font);
    
        m_label.set_halign(Gtk::ALIGN_CENTER);
        
        add(m_label);
    }
    
    int main(int argc, char *argv[])
    {
        auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
      
        MainWindow window;
        window.show_all();
      
        return app->run(window);
    }
    

    I am no Pango expert, but I think the problem was the use of:

    Glib::RefPtr<Pango::Context> Gtk::Widget::create_pango_context()
    

    Its description from the docs:

    Creates a new Pango::Context with the appropriate font map, font options, font description, and base direction for drawing text for this widget.

    So this is a copy of the widget's context, not its context. Why set_font_description did not set that copy as the new context is not explained in the docs... In my opinion this looks like an API design flaw. It should at least be mentioned.