GTK and scrolling text view

rubixibuc picture rubixibuc · Dec 6, 2011 · Viewed 15.5k times · Source

This is what I have so far

GtkWidget* createConsoleBox()
{
        GtkWidget* textArea = gtk_text_view_new();
        GtkWidget* scrollbar = gtk_vscrollbar_new(gtk_text_view_get_vadjustment(GTK_TEXT_VIEW(textArea)));
        GtkWidget* textEntry = gtk_entry_new();

        GtkWidget* console = gtk_table_new(3, 2, FALSE);

        gtk_table_attach_defaults(GTK_TABLE(console), textArea, 0, 1, 0, 1);
        gtk_table_attach_defaults(GTK_TABLE(console), scrollbar, 1, 2, 0, 1);

        gtk_table_attach_defaults(GTK_TABLE(console), textEntry, 0, 2, 1, 2);

        return console;

}

I want the text view to be scrollable as the text begins to fill the box, but the box keeps on expanding to accommodate more text. How to do I limit the size of the text view and create a scrollable text view.

Thanks in advance :-)

Answer

ptomato picture ptomato · Dec 7, 2011

I'm afraid you've misunderstood how scrollbars work in GTK; usually you don't create a scrollbar directly, but you place the widget you would like to scroll in a GtkScrolledWindow. This creates scrollbars automatically and connects them to the widget inside the scrolled window; in your case, the text view.

Here's what your createConsoleBox() function should look like:

GtkWidget* createConsoleBox()
{
    GtkWidget* textArea = gtk_text_view_new();
    GtkWidget* scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
    GtkWidget* textEntry = gtk_entry_new();
    GtkWidget* console = gtk_table_new(3, 1, FALSE);

    gtk_container_add(GTK_CONTAINER(scrolledwindow), textArea);
    gtk_table_attach_defaults(GTK_TABLE(console), scrolledwindow, 0, 1, 0, 1);
    gtk_table_attach_defaults(GTK_TABLE(console), textEntry, 0, 1, 1, 2);

    return console;
}