无法在gtkmm中向窗口添加多个按钮?

时间:2016-04-16 09:44:01

标签: c++ gtk gtkmm

我仍然不熟悉使用widget工具包,但我认为这应该可行。我从developer.gnome.org复制了这段代码,并将自己的对象(button2)添加到Buttons类中,但只有原始的m_button显示在窗口中。 buttons.h的内容:

    #ifndef GTKMM_EXAMPLE_BUTTONS_H
    #define GTKMM_EXAMPLE_BUTTONS_H

    #include <gtkmm/window.h>
    #include <gtkmm/button.h>

    class Buttons : public Gtk::Window
    {
    public:
        Buttons()
        {
        m_button.add_pixlabel("info.xpm", "hi");
        button2.add_pixlabel("info.xpm", "hello");

        set_title("Pixmap'd buttons!");
        set_border_width(10);

        m_button.signal_clicked().connect( sigc::mem_fun(*this,
          &Buttons::on_button_clicked) );

        add(button2);
        add(m_button);

        show_all_children();
        }

        virtual ~Buttons()
        {
        }

    protected:
        //Signal handlers:
        void on_button_clicked()
        {
        }

        //Child widgets:
        Gtk::Button button2;
        Gtk::Button m_button;
        };

        #endif //GTKMM_EXAMPLE_BUTTONS_H

main.cpp的内容:

    #include "buttons.h"
    #include <gtkmm/application.h>

    int main(int argc, char *argv[])
    {
    Glib::RefPtr<Gtk::Application> app =
    Gtk::Application::create(argc, argv,
    "org.gtkmm.examples.base");

    Buttons buttons;

    return app->run(buttons);
    }

1 个答案:

答案 0 :(得分:4)

我目前也在学习Gtkmm,所以这可能不是最好的答案,但我认为这样做的正确方法是添加Gtk :: Box对象,然后将Gtk :: Buttons添加到Gtk: :箱

我就是这样做的。此外,我已将您的标题gtkmm_example_buttons.h拆分为gtkmm_example_buttons.hpp和gtkmm_example_buttons.cpp我也将按钮名称m_button更改为button1以匹配button2名称,因为它具有一致性。

//gtkmm_example_buttons.hpp
#pragma once //used instead of the ifdef

#include <gtkmm/window.h>
#include <gtkmm/button.h>
#include <gtkmm/box.h>

class Buttons : public Gtk::Window
{
public:
Buttons();
virtual ~Buttons();

protected:
void on_button_clicked();
Gtk::Button button1, button2;
Gtk::Box box1;
};

此外,我已经删除了信号处理,因为它们只会使代码更复杂。稍后您将了解更多信息。

//gtkmm_example_buttons.cpp
#include "gtkmm_example_buttons.hpp"
#include <gtkmm/window.h>
#include <gtkmm/button.h>
#include <gtkmm/box.h>

Buttons::Buttons()
{
button1.add_pixlabel("info.xpm", "hi");
button2.add_pixlabel("info.xpm", "hello");

set_title("Pixmap'd buttons!");
set_border_width(10);
add(box1);

box1.pack_start(button1);
box1.pack_start(button2);

show_all_children();
}

Buttons::~Buttons()
{
}

void Buttons::on_button_clicked()
{
}

主要:

//main.cpp
#include "gtkmm_example_buttons.hpp"
#include <gtkmm.h>

int main (int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.test");
//Shows the window and returns when it is closed.

Buttons buttons;
return app->run(buttons);
}