I’m practicing a bit with Gtk+. I’ve been abel to create a window, with a working menu.
I can create test objects(basically, a square, asking the user to input the side length) and store them in a vector, but I can’t list them.
What I want is to show a scrolled window listing all of the stored objects, something like:
_Square 1-side:7_
_Square 2-side:25_
Until now, I could show the scrolled window with a text label, but none of the info about the stored objects.
Here’s the code that I have tried:
Gtk::Dialog dialog("Listing Squares",false,true);
dialog.set_default_size(500,30);
Gtk::Button close("Close");
close.signal_clicked().connect( sigc::mem_fun(*this,&Window::onFileListButtonClose) );
Gtk::VBox* vbox = dialog.get_vbox();
Gtk::ScrolledWindow sw;
sw.set_policy(Gtk::POLICY_AUTOMATIC,Gtk::POLICY_AUTOMATIC);
/** FETCH FROM ARRAY*/
for(unsigned int i(0); i<vc.size();++i){
Gtk::Label label( "Square number " + i );
sw.add( label );
}
sw.show_all_children();
vbox->pack_start( sw );
vbox = 0;
dialog.add_action_widget(close,1);
dialog.show_all_children();
dialog.run();
[EDIT:]
1) vc is a std::vector. It is a class attribute.
2) The piece of code for asking the user to input the length of the square and storing it in vc.
void Window::onMenuFileNew(void) {
Gtk::Dialog dialog("New Square",true,true);
dialog.set_default_size(70,20);
dialog.set_has_separator(true);
Gtk::Button close("Close");
entry.set_max_length(2);
entry.set_text("");
close.signal_clicked().connect( sigc::mem_fun(*this,&Window::onFileNewButtonClose) );
Gtk::Label lab("Square side length:");
Gtk::VBox* vbox = dialog.get_vbox();
vbox->pack_start( lab );
vbox->pack_start( entry );
vbox = 0;
dialog.add_action_widget(close,1);
dialog.show_all_children();
dialog.run();
}
void Window::onFileNewButtonClose(void) {
int side = atoi( (entry.get_text()).c_str() );
vc.push_back(Cuadrado( side ));
}
Any help would be appreciated. 🙂
PS: Before trying to list the squares, I created some of them!
According to the documentation, the
addmember function accepts widgets by reference. This means that the objects you pass here must exist throughout the lifetime of the container referencing them. In theforloop, they cease to exist as soon as the loop makes one iteration, if you create the labels before the loop, they cease to exist at the end of the function. You run into the equivalent of this: Returning a reference to a local or temporary variable.Now, this is a little bit shooting in the dark because I don’t really know Gtk and I don’t know if the widget is copied somewhere else, so that the original may be destructed, but it looks the way I described it above from a purely C++ point of view.
Just to make sure this is the culprit, define all your labels globally to your application and see if they appear. If they do, you’ll know that you need to declare the
labels in a way that they are alive (e.g. on heap) after that function/loop are over (and still can be destroyed appropriately).