zrneely
zrneely

Reputation: 1942

Using GTK+, how do I add a Label to a Box after it's created?

Here's some code I've been working on (in Rust, using the excellent gtk-rs bindings):

use gtk;
use gtk::prelude::*;

struct LabelViewer {
    pub container: gtk::ScrolledWindow,
    layout: gtk::Box,
    fields: Vec<gtk::Label>,
}
impl LabelViewer {  
    pub fn new() -> Self {
        let container = gtk::ScrolledWindow::new(None, None);
        let layout = gtk::Box::new(gtk::Orientation::Vertical, 5);
        container.add(&layout);
        LabelViewer {
            container: container,
            layout: layout,
            fields: Vec::new(),
        }
    }
    pub fn set_labels(&mut self, labels: &[String]) {
        for label in self.fields.drain(..) {
            self.layout.remove(&label);
        }
        for label in labels.iter().map(|l| gtk::Label::new(Some(l))) {
            self.layout.pack_start(&label, false, false, 0);
            self.fields.push(label);
        }
    }
}

When I create a LabelViewer and add its container to my Window, I see the border of the ScrolledWindow, indicating that it is indeed being added. However, when I call set_labels, no labels are actually rendered.

I have some experience with Swing (from Java), but this is my first time using GTK. Based on my past experience I tried invalidating the container with queue_draw, after calling set_labels, but that didn't have any effect. It may not be relevant, but I call set_labels before gtk::main().

Upvotes: 2

Views: 1251

Answers (1)

andlabs
andlabs

Reputation: 11588

Newly created GtkWidgets are initially hidden. You need to call show() or show_all() on them to make them visible (the latter will recursively show a container's children). This means you have to issue that call yourself if you add widgets after you call show_all() on a window. In your case, you can either call show() individually for each label or call show_all() on self.layout after adding all the labels.

Upvotes: 3

Related Questions