GTK2如何在状态栏中居中显示进度条?
GTK2.24状态栏进度条居中问题解决
问题描述
在GTK2.24环境下,使用以下代码在状态栏中添加进度条时,进度条无法水平居中;但相同代码在GTK3.24及以上版本中显示正常。
异常显示效果:
问题代码:
GtkStyle *style = gtk_widget_get_style (progressbar9); PangoFontDescription *desc = pango_font_description_copy (style->font_desc); pango_font_description_set_size (desc, 8 * PANGO_SCALE); gtk_widget_modify_font (progressbar9, desc); pango_font_description_free (desc); alignment = gtk_alignment_new (0, 0, 0, 0); // or 0, 0.5, 0, 0 gtk_widget_set_name (progressbar9, "progressbar9"); gtk_rc_parse_string ("style \"progressbar9\"\n" "{\n" "GtkProgressBar::min-horizontal-bar-height = 16\n" "GtkProgressBar::yspacing = 0\n" "}\n" "widget \"*.progressbar9\" style \"progressbar9\""); gtk_container_add (GTK_CONTAINER (alignment), progressbar9); gtk_widget_show (alignment); gtk_box_pack_end (GTK_BOX (gtk_statusbar_get_message_area (GTK_STATUSBAR (statusbar))), alignment, FALSE, FALSE, 0);
解决方法
针对GTK2.24的布局特性,需调整两个关键部分:
修正GtkAlignment初始化参数
GtkAlignment的四个参数为xalign, yalign, xscale, yscale,要实现水平居中,需将xalign设为0.5(水平居中对齐),xscale设为1.0(让容器在水平方向填充父控件的可用空间):// 水平居中,垂直居中,水平拉伸填充,垂直不拉伸 alignment = gtk_alignment_new(0.5, 0.5, 1.0, 0.0);调整状态栏容器的pack参数
使用gtk_box_pack_end时,将expand和fill参数设为TRUE,让GtkAlignment占据状态栏消息区域的全部水平空间,这样进度条的居中效果才能在整个状态栏宽度上体现:gtk_box_pack_end(GTK_BOX(gtk_statusbar_get_message_area(GTK_STATUSBAR(statusbar))), alignment, TRUE, TRUE, 0);可选:确保自定义样式生效
如果进度条的自定义样式未正确应用,可在设置widget名称和RC样式后添加:gtk_widget_reset_style(progressbar9);
修改后的完整代码示例:
GtkStyle *style = gtk_widget_get_style (progressbar9); PangoFontDescription *desc = pango_font_description_copy (style->font_desc); pango_font_description_set_size (desc, 8 * PANGO_SCALE); gtk_widget_modify_font (progressbar9, desc); pango_font_description_free (desc); // 修正Alignment参数 alignment = gtk_alignment_new(0.5, 0.5, 1.0, 0.0); gtk_widget_set_name (progressbar9, "progressbar9"); gtk_rc_parse_string ("style \"progressbar9\"\n" "{\n" "GtkProgressBar::min-horizontal-bar-height = 16\n" "GtkProgressBar::yspacing = 0\n" "}\n" "widget \"*.progressbar9\" style \"progressbar9\""); // 确保样式生效 gtk_widget_reset_style(progressbar9); gtk_container_add (GTK_CONTAINER (alignment), progressbar9); gtk_widget_show (alignment); // 修正pack参数 gtk_box_pack_end(GTK_BOX(gtk_statusbar_get_message_area(GTK_STATUSBAR(statusbar))), alignment, TRUE, TRUE, 0);
内容的提问来源于stack exchange,提问作者luigifab
相关产品推荐
相关产品推荐

