skuroedov
skuroedov

Reputation: 77

gtkmm: add widgets that are not fields of class

I would like to add to gtkmm widgets that are not fields of class (I declare them in method).

I tried this:

class MyWidget : public Gtk::Window {
public:
    MyWidget();
    virtual MyWidget();
}

MyWidget::MyWidget() {
    Gtk::Label label("my label");
    add(label);
    label.show();
}

But it does not shwo anthing.

But when i declare label in class and extend method by it, it works:

class MyWidget : public Gtk::Window {
public:
    MyWidget();
    virtual MyWidget();
protected:
    Gtk::Label label;
}

MyWidget::MyWidget() : label("my label") {
    add(label);
    label.show();
}

What am I doing wrong?

Upvotes: 0

Views: 146

Answers (1)

pan-mroku
pan-mroku

Reputation: 891

A widget created in such way is destroyed with the closing bracket of the method. Please read this tutorial about memory management.

Personally I'd propose using dynamic allocation with make_managed() and add(). It's very easy to use and I have never had any problems when using that.

MyWidget::MyWidget() {
  auto* label = Gtk::make_managed<Gtk::Label>("my label");
  add(*label);
  label->show();
}

Upvotes: 1

Related Questions