A Switch has two positions, on and off. This example shows how you can use multiple switches together to control which Image is shown in the window. The pictures used in this example can be downloaded here.
The window will contain a "broken image" icon instead of a picture if picture files named
Red fox photo by Rob Lee, licensed CC-By
Gentoo penguin photo by Ken Funakoshi, licensed CC-By-SA
Fruit bat photo by Shek Graham, licensed CC-By
Mute swan photo by Mindaugas Urbonas, licensed CC-By-SA
Photo credits and licensing information are shown in the application's AboutDialog. Always remember to credit the original artist when using Creative Commons-licensed works!
These are the libraries we need to import for this application to run. Remember that the line which tells GNOME that we're using Gjs always needs to go at the start.
All the code for this sample goes in the SwitchExample class. The above code creates a Gtk.Application for our widgets and window to go in.
Before we call _buildUI to create the window and the widgets inside it, we need to call _initMenus, which tells GNOME to create the menu. We can put the actual code for _initMenus after the code for _buildUI, since it doesn't matter what order we put them in so long as _initMenus is called first in _onStartup.
The _buildUI function is where we put all the code to create the application's user interface. The first step is creating a new Gtk.ApplicationWindow to put all our widgets into.
Each time a Switch is flipped, this function checks to see which of the two Switches are active afterwards, using the Switches' built-in get_active() function. It then changes the Image accordingly. You can change the filenames around as you like, so long as you have pictures to go with them.
The first step is building the GMenu that the "About" button goes into. This is the menu that appears when you click the application's name in the upper-left corner of the screen, next to the Activities menu. Our menu only has two options in it: About, and Quit.
An AboutDialog has a lot of different things you can set, to credit everyone who worked on the application and leave a note to whomever reads it. In this case, the copyright section contains our note and credits the original photographers, while the artists section shows you a list of the photographers with links to the original photos when you click the Credits button. The web URLs put after their names in the array turn their names into clickable links in the Credits section.
Finally, we create a new instance of the finished SwitchExample class, and set the application running.
GMenu
GSimpleAction
Gtk.Application
Gtk.ApplicationWindow
Gtk.Grid
Gtk.Image
Gtk.Label
Gtk.Switch