2

i'm getting this error when i try to compile the first gtk.grid in elementary.io/en/docs/code/getting-started#gtk-grid

my code;

int main(string[] args) {
  Gtk.init (ref args);
  var window = new Gtk.Window ();
  window.title = "project4";

  var grid = new Gtk.Grid ();
  grid.orientation = Gtk.Orientation.VERTICAL;
  grid.add (new Gtk.Label ("Label 1"));
  grid.add (new Gtk.Label ("Label 2"));

  this.add (grid);

  window.show_all ();
  Gtk.main ();
  return 0;
}

right?

Note: when i change "this.add (grid);" for "window.add (grid);" my compilation works without any error and i run the application with "./"

Is it correct?

output

2

It looks like the docs are a bit unclear about this. Your fix is absolutely correct. You want to add your Gtk.Grid to a Gtk.Window as the window's widget. By using window.add (grid) you're doing exactly that, so it's fine that way.

Now let's talk about what the docs are actually trying to say in the paragraph about GtkGrid. Most of the time, you don't want to create a Gtk.Window object. You want to create a custom class based on Gtk.Window which configures the Gtk.Window-specific attributes and adds all your widgets. Take a look at how Pantheon Calculator is doing it: This is the MainWindow-class. It's a class which inherits Gtk.Window and handles all the logic inside its constructor. The custom window is used here which is a Granite.Application created by the main function.

this is always referring to the current class you're in - so you can only use this.add (...) when you're actually in the Gtk.Window you're using.

You might notice the linked class actually doesn't use this. Why? Because you can call a function inside a class and it will look for a function named that way in your class and inherited classes. That's why you can simply use add (...) in your window class as well. However, using this might be a nice rule because you are always aware of the function's context you just called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.