Simple example

Simple example – To get started easily

Simple example

In this example, we will create a combo box, add an array of key/value pairs and display the currently selected pair in a label.

Simple Gtk2_IndexedComboBox example

<?php
require_once 'Gtk2/IndexedComboBox.php';

//display this data
$arData = array(
    
1   => 'Germany',
    
2   => 'United Kingdom',
    
3   => 'Spain',
    
4   => 'France'
);

//Create combo and set the array
$combo = new Gtk2_IndexedComboBox();
$combo->set_array($arData);
//make #2 active
$combo->set_active_key(2);

//trace changes
$combo->connect('changed''comboChanged'$lbl);

function 
comboChanged($combo$lbl)
{
    
$lbl->set_text(
        
"Combo changed:\r\n"
        
'Key: '   $combo->get_active_key() . "\r\n"
        
'Value: ' $combo->get_active_text()
    );
}

//some label to display changes
$lbl = new GtkLabel("Status\r\n\r\n");

//standard stuff
$vbox = new GtkVBox();
$vbox->pack_start($combo);
$vbox->pack_start($lbl);

$wnd = new GtkWindow();
$wnd->connect_simple('destroy', array('Gtk''main_quit'));
$wnd->add($vbox);
$wnd->show_all();
Gtk::main();
?>

At first, we create a new combo widget object. You already could pass the array of data in the constructor if you wanted to, but here we use the set_array() method to do this. After providing the data, entry with id 2 is made active/pre-selected.

Whenever the selection changes, the example displays the selected key and value in a label below the combo box. We use get_active_key() to retrieve the key, and get_active_text() to retrieve the value.