【问题标题】:Gtk::Window add grid is not showing my child widgetsGtk::Window 添加网格未显示我的子小部件
【发布时间】:2020-10-24 02:53:10
【问题描述】:

我将两个小部件附加到一个网格;一个标签和一个旋转按钮,然后将网格添加到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, 0, 10);
    auto spinbutton = Gtk::SpinButton(adjustment);

    grid.set_column_homogeneous(true);
    grid.attach(label     , 0, 0, 1, 1);
    grid.attach(spinbutton, 1, 0, 1, 1);

    add(grid);

    show_all();
}

int main()
{
    auto application = Gtk::Application::create("test.focus.spinbutton");

    SpinButtonExample test;

    return application->run(test);
}

但是,如果我使用 glade 文件,它可以正常工作,但我想用代码来做,但我被卡住了......

【问题讨论】:

    标签: c++ gtk gtkmm3


    【解决方案1】:

    由于您的 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, 0, 10);
        auto spinbutton = Gtk::make_managed<Gtk::SpinButton>(adjustment);
    
        grid.set_column_homogeneous(true);
        grid.attach(label      , 0, 0, 1, 1);
        grid.attach(*spinbutton, 1, 0, 1, 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多