[按下时将图像添加到按钮上

问题描述 投票:0回答:1
button1_on_image = Gtk::manage(new Gtk::Image{"button1_on.png"});   // Load icon
button1_off_image = Gtk::manage(new Gtk::Image{"button1_off.png"}); //   images
button1 = Gtk::manage(new Gtk::ToolButton{*button1_off_image});  // Create button
button1->set_tooltip_markup("Select one stick");                //   with image
button1->signal_clicked().connect(sigc::mem_fun(*this, 
    &Main_window::on_button1_click));
toolbar->append(*button1);

这是一段代码片段,显示了我如何成功按下按钮。问题是,当单击它时,我希望显示“ button1_on.png”而不是“ button1_off.png”,但我不知道该怎么做。

c++ user-interface gtkmm
1个回答
0
投票

这是一个满足您需求的代码段:

  1. 最初创建窗口时,按钮为“关”。
  2. 单击按钮时,按钮将状态更改为“开”。

请注意,这是一个最小的示例,因此再次单击该按钮不会将其状态更改回“开”,但是如果您需要,我将把这部分留给您。

#include <gtkmm.h>

int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "buttons.on.off");

    // Load images:
    Gtk::Image button1_on_image{"button1_on.png"};
    Gtk::Image button1_off_image{"button1_off.png"};

    // Create button:
    Gtk::ToolButton button1{button1_off_image};
    button1.set_tooltip_markup("Select one stick");

    // Create handler (as a lambda):
    const auto handler = [&button1, &button1_on_image, &button1_off_image]()
                         {
                             // We change to "on" here (when clicked):
                             button1.set_icon_widget(button1_on_image);

                             // We make it visible:
                             button1.show_all();
                         };

    button1.signal_clicked().connect(handler);

    // Add the button to the window.
    Gtk::Window window;
    window.add(button1);

    // Make the window visible:
    window.show_all();

    return app->run(window);
}

我简化了您的代码段:

  1. 列表项
  2. 我将所有内容都放在堆栈上(没有new)。
  3. 处理程序是lambda。

我认为它使语法更清晰。

© www.soinside.com 2019 - 2024. All rights reserved.