[英]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): 这是我一直在努力的一些代码(在Rust中,使用出色的gtk-rs绑定):
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. 当我创建一个LabelViewer
并将其容器添加到我的窗口中时,我看到了ScrolledWindow的边框,表明确实已添加了它。 However, when I call set_labels
, no labels are actually rendered. 但是,当我调用set_labels
,实际上不呈现任何标签。
I have some experience with Swing (from Java), but this is my first time using GTK. 我有使用Swing(来自Java)的经验,但这是我第一次使用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. 根据我过去的经验,在调用set_labels
,我尝试使用queue_draw
使容器无效,但这没有任何效果。 It may not be relevant, but I call set_labels
before gtk::main()
. 可能不相关,但是我在 gtk::main()
之前调用set_labels
。
Newly created GtkWidgets are initially hidden. 最初隐藏了新创建的GtkWidget。 You need to call show()
or show_all()
on them to make them visible (the latter will recursively show a container's children). 您需要在它们上调用show()
或show_all()
以使其可见(后者将递归显示容器的子代)。 This means you have to issue that call yourself if you add widgets after you call show_all()
on a window. 这意味着,如果在窗口上调用show_all()
之后添加了小部件,则必须发出一个自己调用的问题。 In your case, you can either call show()
individually for each label or call show_all()
on self.layout
after adding all the labels. 对于您的情况,可以为每个标签单独调用show()
,也可以在添加所有标签后在self.layout
上调用self.layout
show_all()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.