Search code examples
gtkgtk3vala

gtk_container_add: assertion 'GTK_IS_WIDGET (widget)' failed


public class Epoch.MainWindow : Gtk.ApplicationWindow {
    private Gtk.Grid grid;
    
    private Epoch.LabelsGrid labels;
    private Epoch.PreferencesView preferences_view;
    private Epoch.MainView main_view;
    
    public MainWindow (Application app) {
        Object (
            application: app,
            icon_name: "com.github.Suzie97.epoch",
            resizable: false,
            title: _("Epoch"),
            width_request: 500
        );
    }
    
    construct {
        get_style_context ().add_class ("rounded");
        set_keep_below (true);
        stick ();
        
        var preferences_button = new Gtk.Button.from_icon_name ("open-menu-symbolic", Gtk.IconSize.SMALL_TOOLBAR);
        preferences_button.valign = Gtk.Align.CENTER;
        
        var preferences_stack = new Gtk.Stack ();
        preferences_stack.add (preferences_view);
        preferences_stack.add (main_view);
        preferences_stack.transition_type = Gtk.StackTransitionType.SLIDE_LEFT;
        
        var headerbar = new Gtk.HeaderBar ();
        headerbar.show_close_button = true;
        
        var headerbar_style_context = headerbar.get_style_context ();
        headerbar_style_context.add_class ("default-decoration");
        headerbar_style_context.add_class (Gtk.STYLE_CLASS_FLAT);
        
        headerbar.pack_end (preferences_button);
        
        set_titlebar (headerbar);
        
        var main_box = new Gtk.Box (Gtk.Orientation.VERTICAL, 0);
        main_box.pack_start (preferences_stack, true, true);
        add (main_box);
        
        show_all ();
        
        preferences_view = new Epoch.PreferencesView ();
        
        preferences_button.activate.connect (() => {
                preferences_stack.visible_child = preferences_view;
        });
        
    //     public override bool configure_event (Gdk.EventConfigure event) {
    //     int root_x, root_y;
    //     get_position (out root_x, out root_y);
    //     Epoch.settings.set_int ("window-x", root_x);
    //     Epoch.settings.set_int ("window-y", root_y);

    //     return base.configure_event (event);
    }
}

The following error is displayed when I compile, enter image description here

I want the app to switch to the preferences view when the button on the right side of the header bar is clicked, enter image description here

Only, the headerbar is displayed when as you can see.

Why is this happening? How do I solve it?


Solution

  • preferences_stack.add (preferences_view);
    preferences_stack.add (main_view);
    

    You haven't initialized preferences_view yet, and you never initialize main_view. That's where your second and third errors are coming from: gtk_container_add() is complaining that the widget you are trying to add is not actually a widget, but rather null, because you haven't initialized that variable yet.