5

In C, I can autoconnect signals with this code:

gtk_builder_connect_signals (builder, NULL)

How to do this in C++ with GTKmm?

sjsam
  • 21,411
  • 5
  • 55
  • 102
drmgc
  • 171
  • 3
  • 9

2 Answers2

4

You cannot use Glade to connect your signals when using gtkmm, you need to do that manually.

    Glib::RefPtr builder = Gtk::Builder::create_from_file("glade_file.ui");

    Gtk::Window *window1 = 0;
    builder->get_widget("window1", window1);

    Gtk::Button *button1 = 0;
    builder->get_widget("button1", button1);
    // get other widgets
    ...

    button1->signal_clicked().connect(sigc::mem_fun(*this, &button1_clicked));

Have a look at these answers :

https://stackoverflow.com/a/3191472/1673000

https://stackoverflow.com/a/1637058/1673000

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Manmohan Bishnoi
  • 791
  • 13
  • 37
  • This is the right approach. I don't think there will be any shortcuts to connect class methods to glade signal handlers. – sjsam May 08 '20 at 02:14
  • 1
    @sjsam There's also an interesting feature [`get_widget_derived`](https://developer.gnome.org/gtkmm-tutorial/stable/sec-builder-using-derived-widgets.html.en) that allows you to do this within constructor of your widget class, making code better organized. – val - disappointed in SE Sep 23 '20 at 06:24
1

Of course you can, there is nothing wrong with mixing C and C++ code.

here is an example code that assumes the signal handler onComboBoxSelectedItemChange is set from glade on a GtkComboBox.

#include <gtkmm.h>
#include <string>

namespace GUI{

int init(){
    auto app = Gtk::Application::create();
    Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("./res/GUI.glade");
    gtk_builder_connect_signals(builder->gobj(), NULL);

    Gtk::Window* mainWindow = nullptr;

    builder->get_widget("mainWindow", mainWindow);
    return app->run(*mainWindow);
}

extern "C"
void onComboBoxSelectedItemChange(GtkComboBox *widget, gpointer user_data){
    int selectedIndex = gtk_combo_box_get_active(widget);
    Gtk::MessageDialog dialog(std::to_string(selectedIndex).c_str());
    dialog.run();
}

}

int main(){
    return GUI::init();
}

you can build using

g++ -rdynamic -std=c++11 test.cpp $(pkg-config --cflags --libs gtkmm-3.0)
demon36
  • 377
  • 3
  • 10
  • ` there is nothing wrong with mixing C and C++ code.`. True, but you sacrifice certain C++ advantages like code locality of member functions(and the performance advantages associated with it) in the process of writing and linking plain old fashioned C style functions. Of course, you have certain workarounds but I guess the better option is to manually connect the signals to C++ methods as mentioned in the accepted answer. – sjsam May 05 '20 at 05:43