Skip to content

Commit

Permalink
Add example on how to use Gio::ListModel to populate widgets.
Browse files Browse the repository at this point in the history
  • Loading branch information
hugopl committed Nov 20, 2023
1 parent d20b5db commit 400a168
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions examples/list_widget.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
require "../src/gtk4"

class ModelItem < GObject::Object
@[GObject::Property]
property text : String

def initialize(@text)
super()
end
end

class Model < GObject::Object
include Gio::ListModel

@data = [] of ModelItem

def add_item(text : String)
@data << ModelItem.new(text)
items_changed(position: @data.size - 1, removed: 0, added: 1)
end

@[GObject::Virtual]
def get_n_items : UInt32
@data.size.to_u32
end

@[GObject::Virtual]
def get_item(pos : UInt32) : GObject::Object?
@data[pos]?
end

@[GObject::Virtual]
def get_item_type : UInt64
ModelItem.g_type
end
end

app = Gtk::Application.new("hello.example.com", Gio::ApplicationFlags::None)

def setup_item(obj : GObject::Object) : Nil
list_item = Gtk::ListItem.cast(obj)
list_item.child = Gtk::Label.new
end

def bind_item(obj : GObject::Object)
list_item = Gtk::ListItem.cast(obj)
label = Gtk::Label.cast(list_item.child)
item = ModelItem.cast(list_item.item)
label.label = item.text
end

app.activate_signal.connect do
window = Gtk::ApplicationWindow.new(application: app, title: "List")
window.set_default_size(200, 200)

list = Gtk::ListView.new
model = Model.new
list.model = Gtk::SingleSelection.new(model)

factory = Gtk::SignalListItemFactory.new
factory.setup_signal.connect(->setup_item(GObject::Object))

Check failure on line 61 in examples/list_widget.cr

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, latest)

no overload matches 'Gtk::SignalListItemFactory::SetupSignal#connect' with type Proc(GObject::Object, Nil)

Check failure on line 61 in examples/list_widget.cr

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, latest)

no overload matches 'Gtk::SignalListItemFactory::SetupSignal#connect' with type Proc(GObject::Object, Nil)
factory.bind_signal.connect(->bind_item(GObject::Object))
list.factory = factory

button = Gtk::Button.new(label: "Add Item")
button.clicked_signal.connect do
model.add_item("Some item")
end

box = Gtk::Box.new(:vertical, 6)
box.append(list)
box.append(button)

window.child = box
window.present
end

exit(app.run)

0 comments on commit 400a168

Please sign in to comment.