Search code examples
gtk

How to expand the GTK window containing a really tiny GRID inside a scrolled window?


I have a code containing GTK entries in a GRID, my goal is to append them into the GRID to make a table of values, something like a "spreadsheet". The entries are in the GRID, and the GRID is in a GTK Scrolled window, which is in the main window.

Yet, I am not getting the expected result. The GRID is really tiny, it can be expanded.

Here is what I am getting (image):

What I am getting

Here is what I want (image): What I want

Here is my code:

#include <gtk/gtk.h>

int main(int argc, char **argv){
    gtk_init(&argc, &argv);

    GtkWidget *mainwindow;
    mainwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(mainwindow), "Example");
    g_signal_connect(mainwindow, "destroy", G_CALLBACK(gtk_main_quit), NULL);
    
    int n = 5;
    
    GtkWidget *entries[n][n];   
    GtkWidget *grid;
    GtkWidget *scrolledwindow; 
    
    grid = gtk_grid_new();
    gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
    gtk_grid_set_column_spacing(GTK_GRID(grid), 3);
    
    scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
    
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            entries[i][j] = gtk_entry_new();

            gtk_grid_attach(GTK_GRID(grid), entries[i][j], i, j, 1, 1);
        }
    }
    
    gtk_container_add(GTK_CONTAINER(scrolledwindow), grid);
    
    gtk_container_add(GTK_CONTAINER(mainwindow), scrolledwindow);

    gtk_widget_show_all(mainwindow);

    gtk_main();
    
    return 0;
}

Searching in the internet, I have found this problem: Gtk scroll window size in a grid, but it's in Python, and I don't know, but NULL and NULL, what values I must atribute to a and b in this command: gtk_scrolled_window_new(a, b);


Solution

  • You can use the gtk_scrolled_window_set_propagate_natural_width and gtk_scrolled_window_set_propagate_natural_height functions from GtkScrolledWindow.

    For example, in your snippet:

        // ...
    
        scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
        
        // Use the child widget's natural dimensions when requesting the scrollwindow's
        // own natural size:
        gtk_scrolled_window_set_propagate_natural_width(GTK_SCROLLED_WINDOW(scrolledwindow), true);
        gtk_scrolled_window_set_propagate_natural_height(GTK_SCROLLED_WINDOW(scrolledwindow), true);
    
        for(int i = 0; i < n; i++){
    
        // ...