user877329 user877329 - 1 month ago 13
C++ Question

Set widget initial size

How can I set widget initial size in GTK+3?

I tried

gtk_widget_set_size_request(widget,w,h)
before the widget has been realized, and then
gtk_widget_set_size_request(widget,-1,-1)
to release the constraint (after the widget has been realize). This results in a larger window that has larger size, but the widget was size was minimized (it did not remember my initial size).

MCVE:

//@{"targets":[{"name":"initsize","type":"application","pkgconfig_libs":["gtk+-3.0"]}]}

#include <gtk/gtk.h>

int main()
{
gtk_init(NULL,NULL);
auto window=gtk_window_new(GTK_WINDOW_TOPLEVEL);

auto paned=gtk_paned_new(GTK_ORIENTATION_HORIZONTAL);
gtk_container_add(GTK_CONTAINER(window),paned);

auto scrollbox=gtk_scrolled_window_new(NULL,NULL);
gtk_paned_add1(GTK_PANED(paned),scrollbox);

auto other=gtk_label_new("Right panel");
gtk_paned_add2(GTK_PANED(paned),other);

auto tv=gtk_text_view_new();
gtk_container_add(GTK_CONTAINER(scrollbox),tv);

//Make the widget large
gtk_widget_set_size_request(scrollbox,500,300);
gtk_widget_show_all(window);

//Remove constraint. The new (larger) size of `window` is preserved as
//desired, but `scrollbox` shrinks as a consequence of the constraint
//removal
gtk_widget_set_size_request(scrollbox,-1,-1);

gtk_main();
return 0;
}


Hint: While creating this example, the problem appeared when I added the paned widget.

Here is a screenshot of how the desired initial layout. Initial layout

I achieved this by request sizes for the ScrolledWindow to the right, and for the GLArea to the right (without this, everything collapses to almost zero). After the UI is configured, it should be possible to shrink any of these panels, so the constraint must be removed without affecting any sizes. I also tried to preserve the paned position (get its value, remove constraint, and restore the old position, but that did not work).

Answer Source

The closest solution is probably to reverse the problem and set the size of the main window to the sum of the desired sizes, by using gtk_window_set_default_size(). Then use gtk_paned_set_position () with the value for the leftmost widget. While this is only an approximate solution, it should be sufficient for most applications.