Passing data

The previous examples all use a function with no parameters. While this is often enough, it can be helpful to pass additional information into your signal handling functions. This can be done easily as the connect functionality (mirrored by the Clicked() convenience function) allows for additional parameters to be sent. After the function reference, you can pass additional data parameters, which will be available to the function that executes the callback.

We can demonstrate that by creating a new button and passing this button along with the function to the signal connection:

button := gtk.NewButton()
button.SetLabel(label)
button.Clicked(clicked, button)

In the callback function, we update the function signature to accept a *glib.CallbackContext parameter. This parameter contains the data that was specified when the signal was connected. The data can be accessed using the context's Data() function call.

It's convenient to convert the type of the data returned, but remember to be careful when asserting the new type, as an incorrect type will cause your program to crash:

func clicked(ctx *glib.CallbackContext) {
button := ctx.Data().(*gtk.Button)
log.Println("Button clicked was:", button.GetLabel())
}

Bringing this together in a simple example where we create three buttons with the same callback function, we can see how this data parameter allows us to avoid unnecessary functions being created:

    

Multiple buttons; The clicked function handling multiple buttons' click callbacks

As you may have noticed, the previous code snippet mentioned a new package, glib. Let's look at the different packages that the Go-GTK project consists of and when you might want to use them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.53