Re: [Vala] Setting up a timer with callback event



Arkadi Viner wrote:
My code doesn't compile and the problem is:

main.vala:77.10-77.19: error: syntax error, expected `('
<b>Process return 256  execution time: 0.729512 s</b>

and it points on the lines:
public delegate bool
<http://references.valadoc.org/glib-2.0/bool.html>SourceFunc
(){

return true;
}

I don't sure what is 'delegate' for but I tried to look for the correct
callback function for a timer
in valadoc and I found:
http://references.valadoc.org/glib-2.0/GLib.SourceFunc.html
It looks like this:
"public delegate bool
<http://references.valadoc.org/glib-2.0/bool.html>SourceFunc
();"
so, that's why I have wrote "delegate" for....
So I don't need this "delegate" in my code ?

No. With the "delegate" keyword you define a type for functions. So

  public delegate bool SourceFunc ();

means that the type 'SourceFunc' will represent all functions with no
parameters and a boolean return value. When Timeout.add() expects a
SourceFunc as second parameter this means that you can pass any function
with no parameters and a boolean return value as a parameter.

I have attached a compiling version of your code. As Jan has pointed out
your callback functions must be inside the class (especially since they
access 'timerID'). Make sure that you add the 'my_app_' prefix to your
callback functions in Glade:

  my_app_on_btnActivate_clicked
  my_app_on_btnDeactivate_clicked

These will be the C names of the functions.


Best Regards,

Frederik
using Gtk;

public class MyApp {

        private Window window;
        private uint timerID;

        public MyApp () throws Error {
                var builder = new Builder ();
                builder.add_from_file ("gui.ui");
                builder.connect_signals (this);
                this.window = builder.get_object ("win_main") as Window;
                this.window.destroy += Gtk.main_quit;
        }

        public void run () {
                this.window.show_all ();
                Gtk.main ();
        }

        //This should activate the timer.
        [CCode (instance_pos = -1)]
        public void on_btnActivate_clicked (Button source) {
                timerID = Timeout.add (1000, on_timer_event);
        }

        //This should deactivate the timer..
        [CCode (instance_pos = -1)]
        public void on_btnDeactivate_clicked (Button source) {
                Source.remove (timerID);
        }

        //Timer listener
        public bool on_timer_event () {
                stdout.printf ("timer event");
                return true;
        }
}

int main (string[] args) {
        Gtk.init (ref args);
        try {
                var app = new MyApp ();
                app.run ();
        } catch (Error e) {
                stderr.printf ("Could not load UI: %s\n", e.message);
                return 1;
        }
        return 0;
}



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