Alonso Zamorano
Alonso Zamorano

Reputation: 21

How can i get the number of rows in a ListBox?

Don't know if this is the proper place to ask, but i didn't know where else to :p

Upvotes: 2

Views: 2056

Answers (3)

William Giddings
William Giddings

Reputation: 11

This is how I do it in C.

gint index = 0;
while ( gtk_list_box_get_row_at_index (widget,index++) != NULL ) {
g_print("%d\n",index);
}

Upvotes: 0

José Fonte
José Fonte

Reputation: 4114

If you bind the Gtk.ListBox to a model, by means of bind_model, you then have the GLib.ListModel get_n_items method.

If you didn't then you basically have two ways, keep track of added/removed items or calculate them each time you need the count by means of Gtk.Container @foreach method (Gtk.ListBox inherits from Gtk.Container).

To keep track of the count, you could extend/subclass Gtk.ListBox and override the add/remove methods and keep a property/field with the number of children or connect a signal handler to Gtk.Container add/remove signals and keep that same count.

The easiest way, not so efficient, is to use @foreach method, which iterates by all children and calculate the number. The count will be done on each method invocation. If this is something you would do many times then it will have some impact.

Here is a very basic example, where we add some Gtk.Label to a Gtk.ListBox and, although we know the number of added labels we will calculate them by clicking the button:

using Gtk;

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

    var window = new Window ();
    window.title = "Vala Listbox Example";
    window.border_width = 10;
    window.window_position = WindowPosition.CENTER;
    window.set_default_size (350, 70);
    window.destroy.connect (Gtk.main_quit);

    var box = new Gtk.Box (Orientation.VERTICAL, 5);

    var listbox = new ListBox ();

    int i = 10;
    for (i = 0; i < 10; i++) {
        listbox.add (new Label ("A label"));
    }

    var button = new Button.with_label ("Get count!");
    button.clicked.connect (() => {
        int count = 0;
        listbox.@foreach (() => {
            count++;
        });

        print ("Count = %d\n", count);
    });


    box.add (listbox);
    box.add (button);

    window.add (box);

    window.show_all ();

    Gtk.main ();
    return 0;
}

Suppose we call this file main.vala, compile with:

valac main.vala --pkg gtk+-3.0

Upvotes: 2

theGtknerd
theGtknerd

Reputation: 3753

In Python, it would be len(listbox). In other words, just get the length of the listbox.

Upvotes: 1

Related Questions