042. How to display a popup alert for required fields - Part 2 - OK button centered?

Problem

You have displayed a popup alert box in Part 1.

However, note that the OK button is right aligned. You would like the OK button to be centered as shown below:


Solution

The OK button can be centered by changing the layout style of the dialog action area with GtkButtonBox::set_layout(Gtk::BUTTONBOX_SPREAD)


Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
20   
21   
22   
24   
25   
43   
44   
45   
46   
47   
48   
49   
50   
51   
52   
53   
54   
55   
59   
60   
61   
62   
64   
66   
67   
68   
69   
70   
71   
72   
73   
74   
75   
76   
77   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 150);
$window->connect_simple('destroy', array('Gtk','main_quit'));

$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Display Alert - Part 2");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0, 0);

$vbox->pack_start(new GtkLabel(), 0, 0); // add a small gap

// setup the entry field
$hbox = new GtkHBox();
$vbox->pack_start($hbox, 0, 0);
$hbox->pack_start(new GtkLabel("Please enter your name:"), 0, 0);
$name = new GtkEntry();
$hbox->pack_start($name, 0, 0);
$name->connect('activate', 'on_activate');

// check user input
function on_activate($widget) {
    $input = $widget->get_text();
    echo "name = $input\n";
    if ($input=='') alert("Please enter your name!");
    $widget->grab_focus();
}

// display popup alert box
function alert($msg) {
    $dialog = new GtkDialog('Alert', null, Gtk::DIALOG_MODAL);
    $dialog->set_position(Gtk::WIN_POS_CENTER_ALWAYS);
    $top_area = $dialog->vbox;
    $top_area->pack_start($hbox = new GtkHBox());
    $stock = GtkImage::new_from_stock(Gtk::STOCK_DIALOG_WARNING,
        Gtk::ICON_SIZE_DIALOG);
    $hbox->pack_start($stock, 0, 0);
    $hbox->pack_start(new GtkLabel($msg));
    $dialog->add_button(Gtk::STOCK_OK, Gtk::RESPONSE_OK);
    $dialog->action_area->set_layout(Gtk::BUTTONBOX_SPREAD); // note 1
    $dialog->set_has_separator(false);
    $dialog->show_all();
    $dialog->run();
    $dialog->destroy();
}

$window->show_all();
Gtk::main();

?>

Output

As shown above.

 

Explanation

Add comment


Security code
Refresh