16.4. EntryCompletion Objects

An EntryCompletion is an object that is used with an Entry widget to provide completion functionality. As the user types into the Entry the EntryCompletion will popup a window with a set of strings matching the Entry text.

An EntryCompletion is created using the constructor:

  completion = gtk.EntryCompletion()

You can use the Entry method set_completion() to associate an EntryCompletion with an Entry:

  entry.set_completion(completion)

The strings used by the EntryCompletion for matching are retrieved from a TreeModel (usually a ListStore) that must be set using the method:

  completion.set_model(model)

The EntryCompletion implements the CellLayout interface that is similar to the TreeViewColumn in managing the display of the TreeModel data. The following convenience method sets up an EntryCompletion in the most common configuration - a list of strings:

  completion.set_text_column(column)

This method is equivalent to the following:

  cell = CellRendererText()
  completion.pack_start(cell)
  completion.add_attribute(cell, 'text', column)

To set the number of characters that must be entered before the EntryCompletion starts matching you can use the method:

  completion.set_minimum_key_length(length)

The example program entrycompletion.py demonstrates the use of the EntryCompletion. Figure 16.10, “EntryCompletion” illustrates the program in operation.

Figure 16.10. EntryCompletion

EntryCompletion

The example program starts with a small number of completion strings that can be increased by typing into the entry field and pressing the Enter key. If the string is unique it is added to the list of completion strings.

The built-in match function is a case insensitive string comparison function. If you need a more specialized match function, you can use the following method to install your own match function:

  completion.set_match_func(func, user_data)

The signature of func is:

  def func(completion, key_string, iter, data):

where key_string contains the current contents of the Entry, iter is a TreeIter pointing at a row in the associated TreeModel, and data is user_data. func should return TRUE if the row's completion string should be displayed.

The simple example code snippet below uses a match function to display completion names that begin with the entry contents and have the given suffix, in this case, a name ending in .png for a PNG file.

  ...
  completion.set_match_func(end_match, (0, '.png'))
  ...
  def end_match(completion, entrystr, iter, data):
      column, suffix = data
      model = completion.get_model()
      modelstr = model[iter][column]
      return modelstr.startswith(entrystr) and modelstr.endswith(suffix)
  ...

For example if the user types 'foo' and the completion model contains strings like 'foobar.png', smiley.png', 'foot.png' and 'foo.tif', the 'foobar.png' and 'foot.png' strings would be displayed as completions.