Search code examples
c++gtkmmgtkmm3

Change Toolbutton Icon in gtkmm Toolbar after Toolbutton was clicked


I want to change the Icon of a Toolbutton after the Toolbutton was clicked.

My problem is, when i use the Toolbutton method set_icon_widget() , the current Icon disappears, but the new one doesn't show up. The Toolbutton is still there, but it has no Icon anymore.

Here is my Code:

#include <gtkmm.h>


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

private:
  void clicked();

  Gtk::Box m_vbox;
  Gtk::Image image;
  Gtk::Image image_clicked;
  Gtk::Toolbar toolbar;
  Gtk::ToolButton icon;
  Gtk::ToolButton connected;

};

MainWindow::MainWindow() :
image(Gdk::Pixbuf::create_from_file( "network-transmit-receive.svg")),
image_clicked(Gdk::Pixbuf::create_from_file("network-offline.svg")){

  //Window Configuration
  set_title("Tool Button Icon Test");
  set_default_size(400, 200);
  set_position(Gtk::WIN_POS_CENTER);

  icon.set_icon_widget(image);
  connected.set_icon_widget(image_clicked);

  icon.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::clicked));

  toolbar.set_toolbar_style(Gtk::TOOLBAR_ICONS);
  toolbar.set_icon_size(Gtk::ICON_SIZE_SMALL_TOOLBAR);
  toolbar.set_vexpand_set(false);

  toolbar.add(icon);

  m_vbox.set_orientation(Gtk::ORIENTATION_VERTICAL);
  m_vbox.pack_start(toolbar, Gtk::PACK_SHRINK, 0);
  add(m_vbox);

  show_all_children();

}

void MainWindow::clicked(){
  icon.set_icon_widget(image_clicked);
}


int main (int argc, char *argv[])
{
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "de.example.Toolbutton-Test");

    MainWindow mainwindow;

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

I also tried to remove the current ToolButton and to add a new one with the different Icon, but than the current Toolbutton is removed and the new one is not drawn :-/

Can somebody help me please?


Solution

  • I just found the answer by myself. I can change the icon of the MenuButton by setting a new image to the image object of the MenuButton.

    The clicked Method looks like this now:

    void MainWindow::clicked(){
      image.set(Gdk::Pixbuf::create_from_file("network-offline.svg"));
    }