gtkmm3学习笔记(三)-button

发布于 2021-09-10  1128 次阅读


​在上次的工程上进行修改

首先在ui文件中添加一个button

  <object class="GtkButton" id="button">
    <property name="label" translatable="yes">button</property>
    <property name="visible">True</property>
    <property name="can-focus">True</property>
    <property name="receives-default">True</property>
  </object>

取代box左侧的label,将右侧的label改名。

  <object class="GtkBox" id="box">
    <property name="visible">True</property>
    <property name="can-focus">False</property>
    <property name="homogeneous">True</property>
    <child>
      <object class="GtkButton" id="button">
        <property name="label" translatable="yes">button</property>
        <property name="visible">True</property>
        <property name="can-focus">True</property>
        <property name="receives-default">True</property>
      </object>
      <packing>
        <property name="expand">False</property>
        <property name="fill">True</property>
        <property name="position">0</property>
      </packing>
    </child>
    <child>
      <object class="GtkLabel" id="label">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <property name="label">label</property>
      </object>
      <packing>
        <property name="expand">False</property>
        <property name="fill">True</property>
        <property name="position">1</property>
      </packing>
    </child>
  </object>

编译运行,效果如图

接下来要添加按钮的行为

在.h文件中添加button变量,并添加一个按钮点击事件函数。

#pragma once

#include <gtkmm/box.h>
#include <gtkmm/builder.h>
#include <gtkmm/buttton.h>
#include <gtkmm/headerbar.h>
#include <gtkmm/label.h>
#include <gtkmm/window.h>

class HelloworldWindow : public Gtk::Window {
 public:
  HelloworldWindow();

 private:
  Gtk::HeaderBar *headerbar;
  Gtk::Label *label;
  Gtk::Box *box;
  Gtk::Button *button;
  Glib::RefPtr<Gtk::Builder> builder;

  void onButtonClicked();
};

修改.cpp文件

#include "helloworld-window.h"

HelloworldWindow::HelloworldWindow()
    : Glib::ObjectBase("HelloworldWindow"),
      Gtk::Window(),
      headerbar(nullptr),
      label(nullptr) {
  builder = Gtk::Builder::create_from_resource(
      "/top/immiq/HelloWorld/helloworld-window.ui");
  builder->get_widget("headerbar", headerbar);
  builder->get_widget("label", label);
  builder->get_widget("box", box);
  builder->get_widget("button", button);
  set_titlebar(*headerbar);
  headerbar->show();
  button->signal_clicked().connect(
      sigc::mem_fun(*this, &HelloworldWindow::onButtonClicked));
  add(*box);
}

void HelloworldWindow::onButtonClicked() { label->set_text("Hello, World"); }

点击后,label变为Hello, World

代码中 button->signal_clicked().connect(sigc::mem_fun(*this, &HelloworldWindow::onButtonClicked));将单击信号与自定义函数绑定。

label->set_text(“Hello, World”); 用来更改label文本。