tags:

views:

206

answers:

2

How do I initialize a GtkScrolledWindow to avoid scrollbars by growing as much as possible?

By default it seems to be as small as possible.

Demo code (Quit with SIGINT):

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
    GtkWidget* window;
    GtkWidget* content;
    GtkWidget* sw;

    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    sw = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
         GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
    gtk_container_add(GTK_CONTAINER(window), sw);
    gtk_widget_show(sw);

    content = gtk_button_new_with_label("This is a very, very"
         "very very very very very very very very long text");
    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(sw), content);
    gtk_widget_show(content);

    gtk_widget_show(window);
    gtk_main();

    return 0;
}
A: 

I'm not sure what the proper way to do this is, but I've found that what works best for me is to set the size of the window, and the widgets contained within it usually size themselves correctly:

gtk_window_set_default_size(GTK_WINDOW(window), 1000, 500);

Alternatively, you can set the size of the GtkScrolledWindow:

gtk_widget_set_size_request(window, 500, 250);

Note that in especially this last case, localisation, font sizes, and other such details probably have to be considered when calculationg the size in pixels.

Lars Wirzenius
Sure, this works, but it is an ugly hack, and as you said, does not work except in a few lucky cases. And afaik you can't just query a GTK Widget for its size, can you?
phihag
+1  A: 

I think this both works and is not an ugly hack (much):

int main(int argc, char *argv[]) {
    GtkWidget* window;
    GtkWidget* content;
    GtkWidget* sw;

    GtkRequisition size;
    GtkWidget* viewport;

    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    sw = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
            GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
    gtk_container_add(GTK_CONTAINER(window), sw);
    gtk_widget_show(sw);

    content = gtk_button_new_with_label("This is a very, very"
            "very very very very very very very very long text");
    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(sw), content);
    gtk_widget_show(content);

    gtk_widget_show(window);

    viewport = gtk_widget_get_ancestor(content, GTK_TYPE_VIEWPORT);
    gtk_widget_size_request(viewport, &size);
    gtk_widget_set_size_request(sw, size.width, size.height);

    gtk_main();

    return 0;
}
Kim Reece