Search code examples
c++gtkmm

gtkmm text on a picture


I'd like to have a picture element in my gui with text on it. My goal is to load pictures (for example a waterdrop) and place text on it which stands for a measured humidity (values come from MQTT).

What would be the best way to do this? I don't care if it's a label or any other kind of element (though I'm not happy with misusing a button for that). The text needs to be changable. Im very new to this framework so I didn't get the hang on it yet.

Thank you!


Solution

  • This is an example code. It uses an overlay to stack two widgets, an image and a label:

    #include <gtk/gtk.h>
    
    int main(int argc, char *argv[]) {
    
      GtkWidget *window;
      GtkWidget *image;
      GtkWidget *label;
      GtkWidget *overlay;
    
      gtk_init(&argc, &argv);
    
      window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
      gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
      gtk_window_set_title(GTK_WINDOW(window), "Sandbox");
    
      image = gtk_image_new_from_file("image.png");
      label = gtk_label_new("I've always been too lame\n\
    To see what's before me\n\
    And I know nothing sweeter than\n\
    Champaign from last New Years\n\
    Sweet music in my ears\n\
    And a night full of no fears\n\
    \n\
    But if I had one wish fulfilled tonight\n\
    I'd ask for the sun to never rise\n\
    If God passed a mic to me to speak\n\
    I'd say \"Stay in bed, world,\n\
    Sleep in peace");
    
      overlay = gtk_overlay_new ();
    
      gtk_container_add(GTK_CONTAINER(window), overlay);
    
      gtk_overlay_add_overlay(GTK_OVERLAY(overlay), image);
      gtk_overlay_add_overlay(GTK_OVERLAY(overlay), label);
    
      g_signal_connect(G_OBJECT(window), "destroy",
            G_CALLBACK(gtk_main_quit), NULL);
    
      gtk_widget_show_all(window);
    
      gtk_main();
    
      return 0;
    }