Button (按钮)

5.1.1. 构造函数

可以通过两种方式来创建按钮,你可以在 Gtk::Button 构造函数中指定标签字符串,或者以后调用 set_label() 来指定标签。

如果你想为按钮定义一个快捷键,那么可以在标签字符串中的某个字符前面加上一个下划线,并且指定可选的参数助记符(mnemonic)为 true。例如:

Gtk::Button* pButton = new Gtk::Button("_Something", true);

Stock items have been recommended for use in buttons. From gtkmm-3.10 they are deprecated. They should not be used in newly-written code. However, the documentation of namespace Gtk::Stock shows recommended labels and named icons to show in buttons.

Gtk::Button 同时也是一个容器,因此你可以在其中放任何其它的组件,比如放一个 Gtk::Image 在里面。

Reference

5.1.2. 示例

这个示例创建了一个有图片和文字标签的按钮。

Figure 5-1按钮示例

Source Code

File: buttons.h (For use with gtkmm 3, not gtkmm 2)

#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();
  virtual ~Buttons();

protected:
  //Signal handlers:
  void on_button_clicked();

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

#endif //GTKMM_EXAMPLE_BUTTONS_H

File: buttons.cc (For use with gtkmm 3, not gtkmm 2)

#include "buttons.h"
#include <iostream>

Buttons::Buttons()
{
  m_button.add_pixlabel("info.xpm", "cool button");

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

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

  add(m_button);

  show_all_children();
}

Buttons::~Buttons()
{
}

void Buttons::on_button_clicked()
{
  std::cout << "The Button was clicked." << std::endl;
}

File: main.cc (For use with gtkmm 3, not gtkmm 2)

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

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

  Buttons buttons;

  //Shows the window and returns when it is closed.
  return app->run(buttons);
}

5.1.3. 信号

The Gtk::Button widget has the following signals, but all except the clicked signal are deprecated and should not be used in newly-written code:

pressed

Emitted when the button is pressed. Use Gtk::Widget::signal_button_press_event() instead.

released

Emitted when the button is released. Use Gtk::Widget::signal_button_release_event() instead.

clicked

当按钮按下并抬起时发出。

enter

Emitted when the mouse pointer enters the button's window. Use Gtk::Widget::signal_enter_notify_event() instead.

leave

Emitted when the mouse pointer leaves the button's window. Use Gtk::Widget::signal_leave_notify_event() instead.