Search code examples
gtkvalagenie

How to use the ToolButton clicked signal (in a HeaderBar)?


While creating a simple ToolButton, one can use the clicked.connect interface as in the Toolbar example from the Vala guide. The interface of adding a button to a HeaderBar is similar to what is shown in that example. However, the way of handling the clicked connection seems to be different (or there is something that I am missing).

The following example is of a small text editor, where a open dialog button is packed into the HeaderBar. The clicked.connection syntax, however returns an error.

Here is the code:

[indent=4]
uses
    Gtk

init
    Gtk.init (ref args)

    var app = new Application ()
    app.show_all ()
    Gtk.main ()

// This class holds all the elements from the GUI
class Application : Gtk.Window

    _view:Gtk.TextView

    construct ()

        // Prepare Gtk.Window:
        this.window_position = Gtk.WindowPosition.CENTER
        this.destroy.connect (Gtk.main_quit)
        this.set_default_size (400, 400)


        // Headerbar definition
        headerbar:Gtk.HeaderBar = new Gtk.HeaderBar()
        headerbar.show_close_button = true
        headerbar.set_title("My text editor")

        // Headerbar buttons
        open_button:Gtk.ToolButton = new ToolButton.from_stock(Stock.OPEN)
        open_button.clicked.connect (openfile)

        // Add everything to the toolbar
        headerbar.pack_start (open_button)
        show_all ()
        this.set_titlebar(headerbar)

        // Box:
        box:Gtk.Box = new Gtk.Box (Gtk.Orientation.VERTICAL, 1)
        this.add (box)

        // A ScrolledWindow:
        scrolled:Gtk.ScrolledWindow = new Gtk.ScrolledWindow (null, null)
        box.pack_start (scrolled, true, true, 0)

        // The TextView:
        _view = new Gtk.TextView ()
        _view.set_wrap_mode (Gtk.WrapMode.WORD)
        _view.buffer.text = "Lorem Ipsum"
        scrolled.add (_view)

The open_button.clicked.connect returns at compilation:

text_editor-exercise_7_1.gs:134.32-134.39: error: Argument 1: Cannot convert from `Application.openfile' to `Gtk.ToolButton.clicked'
        open_button.clicked.connect (openfile)

Does the way of handling that signal changes when one uses the HeaderBar widget?

The code is working as long as the line is commented (you may want to add a stub for the openfile function).

Thanks

UPDATE

This question deserves an update, because the error was actually not in the body I attached above.

The error was at the definition of the function. I wrote:

    def openfile (self:Button)

When I should've instead:

    def openfile (self:ToolButton)

Or simply:

    def openfile ()

Solution

  • You didn't include the click handler in your code, using this example stub it works just fine:

    def openfile ()
        warning ("Button clicked")
    

    So I guess that the type signature of your click handler is wrong and that's why the compiler is complaining here.