005. How to right justify the text in GtkLabel?

Problem

You want to right justify the text in GtkLabel as shown below:

How to right justify the text in GtkLabel?


Solution

Use GtkLabel::set_justify()

$label->set_justify(Gtk::JUSTIFY_RIGHT);

Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 100);
$window->modify_bg(Gtk::STATE_NORMAL, GdkColor::parse("#B2D2DE"));
$window->connect_simple('destroy', array('Gtk','main_quit'));
$label = new GtkLabel("hello world!\nthis is line2\nand this is line3");
$label->set_justify(Gtk::JUSTIFY_RIGHT);
$window->add($label);
$window->show_all();
Gtk::main();
?>

Output

As shown above.
 

Explanation

  • A label can contain multiple lines by using \n as line breaks. Note that you have to enclose \n in double quotes, not single quotes.
  • To right justify, use Gtk::JUSTIFY_RIGHT
  • To left justify, use Gtk::JUSTIFY_LEFT
  • To center text, use Gtk::JUSTIFY_CENTER
  • To left-right justify text, use Gtk::JUSTIFY_FILL

Notes

Note that $label->set_justify() only justifies the text within the label. The entire label is still centered relative to the window.

If you wish to produce something similar to the output below, i.e. the whole text right align to the right of GtkWindow:

How to index?

Please refer to this article.

Add comment


Security code
Refresh