July 24, 2018

Creating a GUI with C++, gtkmm and glade



The first impression for the beginner is, that C++ is very complicated if the aim is to create GUI application. Other languages like C# and Java seems to be more comfortable. The major problem is not the language itself, but it is a lack of documentation. I've searched a bit in the internet to find a good documention, but it seems very complicated. Most tutorials about gtkmm are about manually creating the buttons in the sourcecode which is outdated. What today's programmers want is a GUI tool like glade. But how to use glade together with C++? That is unclear, I didn't find a good documentation for that problem, but it seems, that the C community is better informed. Under the URL https://prognotes.net/2015/06/gtk-3-c-program-using-glade-3/ is a nice tutorial given which shows a hello world example which contains of C sourcecode together with the glade editor. I've modified the code a bit for C++ needs and here is my hello world example:

// Glade gui with gtkmm
// g++ -std=c++14 `pkg-config --cflags --libs gtkmm-3.0`main.cpp
// https://prognotes.net/2015/06/gtk-3-c-program-using-glade-3/

#include iostream
#include gtkmm.h
int main(int argc, char *argv[])

  gtk_init(&argc, &argv);
  GtkBuilder *builder = gtk_builder_new(); 
  gtk_builder_add_from_file (builder, "gui.glade", NULL);  
  GtkWidget *window = GTK_WIDGET(gtk_builder_get_object(builder, "mainwindow")); // from XML file
  gtk_builder_connect_signals(builder, NULL);
  g_object_unref(builder);
  gtk_widget_show(window);                
  gtk_main();

  return 0; 
}


The basic idea is to use the Glade gui tool for drag and drop the window and save the XML file as “gui.glade”. Then in the C++ program this XML gets loaded and become visible on the screen. It seems to be a common idea, but it is very hard to find tutorials for such a simple task.
Like I mentioned above in the introduction, the problem is not C++, glade or gtkmm. With these tools everything is fine. The resulting “a.out” application works stable, and the ecosystem is mature. The problem is a lack of documentation. Most programmers are only familiar with Windows GUI system, and here C# replaced the previous C++ entirely. While in contrast under Linux, most developers are only programming textbased-commandline tools and have no need for a nice looking GUI.
I strongly believe, that this will not be the last tutorial for combining glade with C++. Perhaps in the future some extension become possible, for example a more advanced GUI application which is more then a simple hello world example. But for this time, this tutorial is over.

No comments:

Post a Comment