Showing posts with label gtk. Show all posts
Showing posts with label gtk. Show all posts

Saturday, September 29, 2012

Gtk+ tips: Set value of properties in C

In C, if you want to set the value of certain property of a Gtk+ object, you can do it like so
gtk_<type>_set_<property> (GTK_<TYPE> (var_name), <value>);
For example, to set the title of a GtkWindow to "Hello World", do would write
gtk_window_set_title (GTK_WINDOW (window), "Hello World");

This is fine, but what if you want to set the value of a bunch of properties, say for GtkWindow; "app-paintable", "default-width", "default-height", "resizable", and "modal", most beginner would write:

GtkWidget *window = gtk_window_new ();
gtk_widget_set_app_paintable (window), TRUE);
gtk_window_set_default_size (GTK_WINDOW (window), 100,100);
gtk_window_set_resizable (GTK_WINDOW (window), FALSE);
gtk_window_set_modal (GTK_WINDOW (window), TRUE);

Too many characters to type (229 characters excluding spaces and newlines).

I prefer the GObject way  to do this task. The following is the code which does the same thing as the code above, but by using g_object_set:

GtkWidget *window = gtk_window_new ();
g_object_set (G_OBJECT (window),
        "app-paintable", TRUE,
        "default-width", 100, "default-height", 100,
        "resizable", FALSE,
        "modal", TRUE,
        NULL); //the arguments must end with NULL

You have to type much less characters, only 130 characters.  You can also remove the G_OBJECT macro from the code above. Moreover, your code would look more beautiful (in my eyes at least). :)

Tuesday, May 15, 2012

GtkClutterEmbed the Pythonic Way!

The following is a simple clutter-gtk program in python that has an animatable widget. The script is for Gtk+3.0 not Gtk+2.0.

#!/usr/bin/python


from gi.repository import Gtk, Clutter, GtkClutter


storedWidth = 0
storedHeight = 0


def on_clicked(b, actor):
    global storedWidth, storedHeight
    if actor.get_width() != actor.get_stage().get_width():
        storedWidth = actor.get_width()
        storedHeight = actor.get_height()
        width = actor.get_stage().get_width()
        height = actor.get_stage().get_height()
    else:
        width = storedWidth
        height = storedHeight
        
    actor.animatev(Clutter.AnimationMode.EASE_OUT_BOUNCE,
                   500, ["width", "height"], [width, height])
    
GtkClutter.init([])


bttn = Gtk.Button("Foobar")
txtv = Gtk.TextView()
scwn = Gtk.ScrolledWindow()
scwn.add(txtv)
scwn.show_all()
bact = GtkClutter.Actor(contents = scwn)
embd = GtkClutter.Embed()
stge = embd.get_stage()
col = Clutter.Color()
col.from_string("#000")
stge.set_color(col)
vbox = Gtk.VBox()
wndw = Gtk.Window(width_request = 400, height_request = 300)


stge.add_actor(bact)
vbox.pack_start(embd, True, True, 0)
vbox.pack_start(bttn, False, True, 0)
wndw.add(vbox)


wndw.show_all()


bttn.connect("clicked", on_clicked, bact)
wndw.connect("destroy", lambda w: Gtk.main_quit())


Gtk.main()