summaryrefslogtreecommitdiff
path: root/examples/demo/demos/combobox.py
blob: 1215f16c0fc5ac6295e02bf8353df946febf42a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri <johnp@redhat.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
# USA

title = "Combo boxes"
description = """
The ComboBox widget allows to select one option out of a list.
The ComboBoxEntry additionally allows the user to enter a value
that is not in the list of options.

How the options are displayed is controlled by cell renderers.
 """


from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GObject


(PIXBUF_COL,
 TEXT_COL) = range(2)


class MaskEntry(Gtk.Entry):
    __gtype_name__ = 'MaskEntry'

    def __init__(self, mask=None):
        self.mask = mask
        super(MaskEntry, self).__init__()

        self.connect('changed', self.changed_cb)

        self.error_color = Gdk.RGBA()
        self.error_color.red = 1.0
        self.error_color.green = 0.9
        self.error_color_blue = 0.9
        self.error_color.alpha = 1.0

        # workaround since override_color doesn't accept None yet
        style_ctx = self.get_style_context()
        self.normal_color = style_ctx.get_color(0)

    def set_background(self):
        if self.mask:
            if not GLib.regex_match_simple(self.mask,
                                           self.get_text(), 0, 0):
                self.override_color(0, self.error_color)
                return

        self.override_color(0, self.normal_color)

    def changed_cb(self, entry):
        self.set_background()


class ComboboxApp:
    def __init__(self, demoapp):
        self.demoapp = demoapp

        self.window = Gtk.Window()
        self.window.set_title('Combo boxes')
        self.window.set_border_width(10)
        self.window.connect('destroy', lambda w: Gtk.main_quit())

        vbox = Gtk.VBox(homogeneous=False, spacing=2)
        self.window.add(vbox)

        frame = Gtk.Frame(label='Some stock icons')
        vbox.pack_start(frame, False, False, 0)

        box = Gtk.VBox(homogeneous=False, spacing=0)
        box.set_border_width(5)
        frame.add(box)

        model = self.create_stock_icon_store()
        combo = Gtk.ComboBox(model=model)
        box.add(combo)

        renderer = Gtk.CellRendererPixbuf()
        combo.pack_start(renderer, False)

        # FIXME: override set_attributes
        combo.add_attribute(renderer, 'pixbuf', PIXBUF_COL)
        combo.set_cell_data_func(renderer, self.set_sensitive, None)

        renderer = Gtk.CellRendererText()
        combo.pack_start(renderer, True)
        combo.add_attribute(renderer, 'text', TEXT_COL)
        combo.set_cell_data_func(renderer, self.set_sensitive, None)

        combo.set_row_separator_func(self.is_separator, None)
        combo.set_active(0)

        # a combobox demonstrating trees
        frame = Gtk.Frame(label='Where are we ?')
        vbox.pack_start(frame, False, False, 0)

        box = Gtk.VBox(homogeneous=False, spacing=0)
        box.set_border_width(5)
        frame.add(box)

        model = self.create_capital_store()
        combo = Gtk.ComboBox(model=model)
        box.add(combo)

        renderer = Gtk.CellRendererText()
        combo.pack_start(renderer, True)
        combo.add_attribute(renderer, 'text', 0)
        combo.set_cell_data_func(renderer, self.is_capital_sensistive, None)

        # FIXME: make new_from_indices work
        #        make constructor take list or string of indices
        path = Gtk.TreePath.new_from_string('0:8')
        treeiter = model.get_iter(path)
        combo.set_active_iter(treeiter)

        # A GtkComboBoxEntry with validation.

        frame = Gtk.Frame(label='Editable')
        vbox.pack_start(frame, False, False, 0)

        box = Gtk.VBox(homogeneous=False, spacing=0)
        box.set_border_width(5)
        frame.add(box)

        combo = Gtk.ComboBoxText.new_with_entry()
        self.fill_combo_entry(combo)
        box.add(combo)

        entry = MaskEntry(mask='^([0-9]*|One|Two|2\302\275|Three)$')

        Gtk.Container.remove(combo, combo.get_child())
        combo.add(entry)

        # A combobox with string IDs

        frame = Gtk.Frame(label='String IDs')
        vbox.pack_start(frame, False, False, 0)

        box = Gtk.VBox(homogeneous=False, spacing=0)
        box.set_border_width(5)
        frame.add(box)

        # FIXME: model is not setup when constructing Gtk.ComboBoxText()
        #        so we call new() - Gtk should fix this to setup the model
        #        in __init__, not in the constructor
        combo = Gtk.ComboBoxText.new()
        combo.append('never', 'Not visible')
        combo.append('when-active', 'Visible when active')
        combo.append('always', 'Always visible')
        box.add(combo)

        entry = Gtk.Entry()

        combo.bind_property('active-id',
                            entry, 'text',
                            GObject.BindingFlags.BIDIRECTIONAL)

        box.add(entry)
        self.window.show_all()

    def strip_underscore(self, s):
        return s.replace('_', '')

    def create_stock_icon_store(self):
        stock_id = (Gtk.STOCK_DIALOG_WARNING,
                    Gtk.STOCK_STOP,
                    Gtk.STOCK_NEW,
                    Gtk.STOCK_CLEAR,
                    None,
                    Gtk.STOCK_OPEN)

        cellview = Gtk.CellView()
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        for id in stock_id:
            if id is not None:
                pixbuf = cellview.render_icon(id, Gtk.IconSize.BUTTON, None)
                item = Gtk.stock_lookup(id)
                label = self.strip_underscore(item.label)
                store.append((pixbuf, label))
            else:
                store.append((None, 'separator'))

        return store

    def set_sensitive(self, cell_layout, cell, tree_model, treeiter, data):
        """
        A GtkCellLayoutDataFunc that demonstrates how one can control
        sensitivity of rows. This particular function does nothing
        useful and just makes the second row insensitive.
        """

        path = tree_model.get_path(treeiter)
        indices = path.get_indices()

        sensitive = not (indices[0] == 1)

        cell.set_property('sensitive', sensitive)

    def is_separator(self, model, treeiter, data):
        """
        A GtkTreeViewRowSeparatorFunc that demonstrates how rows can be
        rendered as separators. This particular function does nothing
        useful and just turns the fourth row into a separator.
        """

        path = model.get_path(treeiter)

        indices = path.get_indices()
        result = (indices[0] == 4)

        return result

    def create_capital_store(self):
        capitals = (
            {'group': 'A - B', 'capital': None},
            {'group': None, 'capital': 'Albany'},
            {'group': None, 'capital': 'Annapolis'},
            {'group': None, 'capital': 'Atlanta'},
            {'group': None, 'capital': 'Augusta'},
            {'group': None, 'capital': 'Austin'},
            {'group': None, 'capital': 'Baton Rouge'},
            {'group': None, 'capital': 'Bismarck'},
            {'group': None, 'capital': 'Boise'},
            {'group': None, 'capital': 'Boston'},
            {'group': 'C - D', 'capital': None},
            {'group': None, 'capital': 'Carson City'},
            {'group': None, 'capital': 'Charleston'},
            {'group': None, 'capital': 'Cheyeene'},
            {'group': None, 'capital': 'Columbia'},
            {'group': None, 'capital': 'Columbus'},
            {'group': None, 'capital': 'Concord'},
            {'group': None, 'capital': 'Denver'},
            {'group': None, 'capital': 'Des Moines'},
            {'group': None, 'capital': 'Dover'},
            {'group': 'E - J', 'capital': None},
            {'group': None, 'capital': 'Frankfort'},
            {'group': None, 'capital': 'Harrisburg'},
            {'group': None, 'capital': 'Hartford'},
            {'group': None, 'capital': 'Helena'},
            {'group': None, 'capital': 'Honolulu'},
            {'group': None, 'capital': 'Indianapolis'},
            {'group': None, 'capital': 'Jackson'},
            {'group': None, 'capital': 'Jefferson City'},
            {'group': None, 'capital': 'Juneau'},
            {'group': 'K - O', 'capital': None},
            {'group': None, 'capital': 'Lansing'},
            {'group': None, 'capital': 'Lincon'},
            {'group': None, 'capital': 'Little Rock'},
            {'group': None, 'capital': 'Madison'},
            {'group': None, 'capital': 'Montgomery'},
            {'group': None, 'capital': 'Montpelier'},
            {'group': None, 'capital': 'Nashville'},
            {'group': None, 'capital': 'Oklahoma City'},
            {'group': None, 'capital': 'Olympia'},
            {'group': 'P - S', 'capital': None},
            {'group': None, 'capital': 'Phoenix'},
            {'group': None, 'capital': 'Pierre'},
            {'group': None, 'capital': 'Providence'},
            {'group': None, 'capital': 'Raleigh'},
            {'group': None, 'capital': 'Richmond'},
            {'group': None, 'capital': 'Sacramento'},
            {'group': None, 'capital': 'Salem'},
            {'group': None, 'capital': 'Salt Lake City'},
            {'group': None, 'capital': 'Santa Fe'},
            {'group': None, 'capital': 'Springfield'},
            {'group': None, 'capital': 'St. Paul'},
            {'group': 'T - Z', 'capital': None},
            {'group': None, 'capital': 'Tallahassee'},
            {'group': None, 'capital': 'Topeka'},
            {'group': None, 'capital': 'Trenton'}
        )

        parent = None

        store = Gtk.TreeStore(str)

        for item in capitals:
            if item['group']:
                parent = store.append(None, (item['group'],))
            elif item['capital']:
                store.append(parent, (item['capital'],))

        return store

    def is_capital_sensistive(self, cell_layout, cell, tree_model, treeiter, data):
        sensitive = not tree_model.iter_has_child(treeiter)
        cell.set_property('sensitive', sensitive)

    def fill_combo_entry(self, entry):
        entry.append_text('One')
        entry.append_text('Two')
        entry.append_text('2\302\275')
        entry.append_text('Three')


def main(demoapp=None):
    ComboboxApp(demoapp)
    Gtk.main()


if __name__ == '__main__':
    main()