[Vala] widget subclass example for gtk+-3.0




Below is a revised version of the widget subclass example given here:
http://live.gnome.org/Vala/CustomWidgetSamples

It is update to work with gtk+-3.0.   It took me a while to figure out what needed to be changed to work with 
the latest gtk (there may still be some wonky bits there, so feel free to revise further).  Maybe it is 
useful for someone else.

best -august.


----------------------------------------


using Gtk;
using Gdk;
using Cairo;

public class ValaWidget : Widget {

    private static const string TEXT = "Hello World!";
    private static const int BORDER_WIDTH = 10;
    private Pango.Layout layout;
    construct {
        this.layout = create_pango_layout (TEXT);
                                set_has_window (false);         //need this for some reason, don't know why.
                                set_size_request (100, 100);
    }

                public override bool draw        (Cairo.Context cr) {
                        int width  = this.get_allocated_width();
                        int height  = this.get_allocated_height();
                        // In this example, draw a rectangle in the foreground color
                        //Gdk.cairo_set_source_color (cr, this.style.fg[this.state]);
                        cr.set_source_rgba (0.5,0.5,0.5, 1);
                        cr.rectangle (BORDER_WIDTH, BORDER_WIDTH,
                                        width - 2 * BORDER_WIDTH,
                                        height - 2 * BORDER_WIDTH);
                        cr.set_line_width (5.0);
                        cr.set_line_join (LineJoin.ROUND);
                        cr.stroke ();

                        // And draw the text in the middle of the allocated space
                        int fontw, fonth;
                        this.layout.get_pixel_size (out fontw, out fonth);
                        cr.move_to ((width - fontw) / 2,
                                        (height - fonth) / 2);
                        Pango.cairo_update_layout (cr, this.layout);
                        Pango.cairo_show_layout (cr, this.layout);
                        return true;
                }

    static int main (string[] args) {
        Gtk.init (ref args);

        var win = new Gtk.Window (Gtk.WindowType.TOPLEVEL);
        win.border_width = 5;
        win.title = "Widget test";
        win.destroy.connect (Gtk.main_quit);

        var frame = new Frame ("Example Vala Widget");
        win.add (frame);

        var widget = new ValaWidget ();
        frame.add (widget);

        win.show_all ();

        Gtk.main ();
        return 0;
    }
}




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]