问题描述
我在网格上附加了两个小部件;标签和旋转按钮,然后将网格添加到Gtk::Window
我得到这样的空白输出:
#include <gtkmm.h>
class SpinButtonExample : public Gtk::Window {
public:
SpinButtonExample();
};
SpinButtonExample::SpinButtonExample()
{
auto grid = Gtk::Grid();
auto label = Gtk::Label("Hi!");
auto adjustment = Gtk::Adjustment::create(0,10);
auto spinbutton = Gtk::SpinButton(adjustment);
grid.set_column_homogeneous(true);
grid.attach(label,1,1);
grid.attach(spinbutton,1);
add(grid);
show_all();
}
int main()
{
auto application = Gtk::Application::create("test.focus.spinbutton");
SpinButtonExample test;
return application->run(test);
}
但是,如果我使用glade文件,它可以正常工作,但是我想用代码来完成它,但是我被卡住了...
解决方法
由于您的grid
变量(以及所有其他变量)是局部变量,因此SpinButtonExample::SpinButtonExample()
完成后它们将被销毁。
这并非特定于GTK,这是C ++内存管理问题。局部变量在其作用域末尾被破坏。
您需要一种在构造函数完成后保留对小部件的引用的方法。最简单的方法是将grid
声明为类成员。只要包含类存在,它就会一直存在。
您还可以使用new
为对象动态分配内存,但是随后您需要delete
指针以避免内存泄漏。而且您仍然需要存储指针。
对于子小部件,您可以动态分配它们,并在使用Gtk::make_managed
销毁其父对象时销毁它们。在下面的示例中,我已经使用spinbutton
完成了此操作,以显示基本思想。
哪种方法最好取决于情况。
这是您代码的更新版本,显示了保留对小部件的引用的一些方法:
#include <gtkmm.h>
class SpinButtonExample : public Gtk::Window {
public:
SpinButtonExample();
private:
Gtk::Grid grid;
Gtk::Label label;
};
SpinButtonExample::SpinButtonExample()
: grid(),label("Hi!")
{
auto adjustment = Gtk::Adjustment::create(0,10);
auto spinbutton = Gtk::make_managed<Gtk::SpinButton>(adjustment);
grid.set_column_homogeneous(true);
grid.attach(label,1,1);
grid.attach(*spinbutton,1);
add(grid);
show_all();
}
int main()
{
auto application = Gtk::Application::create("test.focus.spinbutton");
SpinButtonExample test;
return application->run(test);
}
另请参阅https://developer.gnome.org/gtkmm-tutorial/stable/sec-memory-widgets.html.en