Creating multiple windows in gtkmm

。_饼干妹妹 提交于 2019-12-25 01:56:21

问题


I started to learn gtkmm library and probably don't understand the way it works. Here's the problem: I've copied simple example from gtkmm tutorial, and want to modify it to create as many windows as I want by clicking the button.

Why can't I just write code like in function on_button_clicked() below?

class Hello : public Gtk::Window {
public:
    Hello() :m_button("create copy") {
        set_border_width(20);
        m_button.signal_clicked().connect(sigc::mem_fun(*this, &Hello::on_button_clicked));
        add(m_button);
        show_all_children();
    }

protected:
    void on_button_clicked();

    Gtk::Button m_button;

};

void Hello::on_button_clicked() {
    Hello new_window;
    new_window.show();
}

int main (int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

    Hello hw;

    return app->run(hw);
}

回答1:


The reason a new window is not displayed is how C++ has been used in the method Hello::on_button_clicked().

The line :

  Hello new_window;

creates a new window with local scope.

  new_window.show();

This marks the window to be shown when GTK+ is back in control.

The line

  }

exits the method and all local variables are destroyed. Which means that new_window is deleted before it can be seen.

To keep the window and have it shown the object must be stored so that it is not automatically destroyed. This could be allocated on the heap and a pointer kept to it in another class for easy access to the window.



来源:https://stackoverflow.com/questions/48215743/creating-multiple-windows-in-gtkmm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!