Example of sorted, filtered list

Perhaps someone will find this useful – perhaps it could be put into
the Gtk examples.

A brief demonstration of

- Gtk::Window

- Gtk::ScrolledWindow

- Gtk::ListStore

- Gtk::TreeView

- Gtk::TreeModelSort

- Gtk::TreeModelFilter

- Gtk::CellRenderText

- Gtk::TreeViewcolumn

- Gtk::TreeIter

By Joe Van D. [email protected]

This is released into the Public Domain

require ‘gtk2’

Create a list store with:

- an Integer (ID)

- a String (date)

- a TrueClass (represents whether or not the row should be shown or

list_store = Gtk::ListStore.new Integer, String, TrueClass

Create a filtered list store that wraps the list store

and set the filter column criteria

list_store_filter = Gtk::TreeModelFilter.new list_store
list_store_filter.visible_column = 2

Create a sorted list store and set the sorting function for the

first column. Note that we are wrapping the sorted model around

filtered model – which in turn wraps the original list store model.

list_store_sort = Gtk::TreeModelSort.new list_store_filter
list_store_sort.set_sort_func(0) { |i, j| i[0] <=> j[0] }

Fill the list store with stuff

10.times do |i|
iter = list_store.append
iter[0] = i
iter[1] = Time.now.to_s
iter[2] = true

Start Gtk


Create a window with a size of 300x300 pixels

window = Gtk::Window.new
window.set_size_request 300, 300
window.signal_connect(“destroy”) { Gtk::main_quit }

Create a scrollable window, with automatic scrollbars, and

pack it into the window

scrolled_window = Gtk::ScrolledWindow.new
scrolled_window.set_policy Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC
window << scrolled_window

Create a treeview, giving it the sorted list store (which is wrapping

tree_view = Gtk::TreeView.new list_store_sort
scrolled_window.add_with_viewport tree_view

Create a CellRenderer that’s in charge of rendering the ID and the

renderer = Gtk::CellRendererText.new

Create the ID column which uses the cell renderer defined above and

is hooked up to the first column of the model. Sorting is turned on

on this column (which also uses the first column in the model to


out what to sort)

id_column = Gtk::TreeViewColumn.new “ID”, renderer, :text => 0
id_column.sort_column_id = 0
tree_view.append_column id_column

Create a column that renders the current time (the second column in

the model

time_column = Gtk::TreeViewColumn.new “Current Time”, renderer, :text =>
tree_view.append_column time_column

Shows everything


Twice a second, we loop through each row in the list and update the


and set half of the rows’ visibility attribute to false and the other

half to true

Gtk::timeout_add(500) do
list_store.each do |model, path, iter|
iter[1] = Time.now.to_s
iter[2] = rand(2) == 1

Starts the Gtk main loop