【问题标题】:Add image to button when pressed按下时将图像添加到按钮
【发布时间】:2020-05-28 02:21:02
【问题描述】:
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】:

    这是一个代码 sn-p 可以满足您的需求:

    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);
    }
    

    我对你的 sn-p 做了一些简化:

    1. 列表项
    2. 我把所有东西都放在堆栈上(没有new)。
    3. 处理程序是一个 lambda。

    在我看来,它使语法更清晰。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-17
      • 2020-08-24
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      相关资源
      最近更新 更多