gtkgtk3gtkmmgtkmm3

How to show shortcuts in ShortcutsWindow?


I would need a simple working example (using Gtkmm 3) of a ShortcutsWindow with just one ShortcutsShortcut that does not use a Gtk::Builder.

I have not been able to find such an example online. I am able to show window however shortcuts do not show.


Solution

  • Here is a very simple example. You can build from it:

    #include <gtkmm.h>
    #include <iostream>
    
    class MyShortcutsWindow : public Gtk::ShortcutsWindow
    {
    
    public:
    
        MyShortcutsWindow();
    
    private:
    
        Gtk::ShortcutsShortcut m_shortcut;
        Gtk::ShortcutsGroup m_group;
        Gtk::ShortcutsSection m_section;
    
    };
    
    MyShortcutsWindow::MyShortcutsWindow()
    {
        // Prints Gtkmm version:
        std::cout << "Gtkmm version : "
                  << gtk_get_major_version() << "."
                  << gtk_get_minor_version() << "."
                  << gtk_get_micro_version()
                  << std::endl;
    
        // 1. Create shorcut:
        // -------------------------------------------------------------
    
        // Set title:
        auto shortcutTitle = m_shortcut.property_title();
        shortcutTitle.set_value("Hit that to search");
    
        // Set type:
        auto shortcutType = m_shortcut.property_shortcut_type();
        shortcutType.set_value(Gtk::SHORTCUT_ACCELERATOR);
    
        // Set accelerator:
        auto shortcutAccelerator = m_shortcut.property_accelerator();
        shortcutAccelerator.set_value("<Ctrl>f");
    
        // 2. Create shortcut group:
        // -------------------------------------------------------------
        m_group.add(m_shortcut);
    
        // 3. Create shortcut section:
        // -------------------------------------------------------------
        m_section.add(m_group);
    
        // Make sure your section is visible. I have found if this is
        // not called, your section won't show until you have tried a
        // search first (weird):
        auto sectionVisibility = m_section.property_visible();
        sectionVisibility.set_value(true);
    
        // 4. Add the section to the window:
        // -------------------------------------------------------------
        add(m_section);
    }
    
    int main(int argc, char *argv[])
    {
        auto app = Gtk::Application::create(argc, argv, "so.question.q66123196");
    
        MyShortcutsWindow window;
        window.show_all();
    
        return app->run(window);
    }
    

    It works with Gtkmm version 3.22.30 in my case. You need at most version 3.20 according to the docs.