I am learning c++ and Gtk+ GUI i am totally newbie and I can't find good tutorials, i have faced this problem so I will write a question here.
When i click on update button i get this error:
Segmentation fault
There is picture below explaining my problem.
Am i doing something wrong?
#include <iostream>
#include <gtkmm-3.0/gtkmm.h>
using namespace std;
Gtk::Window* window = 0;
Gtk::TextView* textview = 0;
Glib::RefPtr<Gtk::TextBuffer> text;
static void quit();
static void update();
int main(int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
//Load the GtkBuilder file and instantiate its widgets:
Glib::RefPtr<Gtk::Builder> refBuilder = Gtk::Builder::create();
try {
refBuilder->add_from_file("window.glade");
}
catch(const Glib::FileError& ex) {
std::cerr << "FileError: " << ex.what() << std::endl;
return 1;
}
catch(const Glib::MarkupError& ex) {
std::cerr << "MarkupError: " << ex.what() << std::endl;
return 1;
}
catch(const Gtk::BuilderError& ex) {
std::cerr << "BuilderError: " << ex.what() << std::endl;
return 1;
}
//Get the GtkBuilder-instantiated Window:
refBuilder->get_widget("window1", window);
if(window) {
window->set_title("GUI");
window->set_size_request(600, 400);
window->set_resizable(false);
text = Gtk::TextBuffer::create();
text->set_text("123");
Gtk::Button* uButton = 0;
refBuilder->get_widget("button2", uButton);
if(uButton) {
uButton->signal_clicked().connect(sigc::ptr_fun(update));
}
Gtk::Button* qButton = 0; // Quit button
refBuilder->get_widget("button1", qButton);
if(qButton) {
qButton->signal_clicked().connect(sigc::ptr_fun(quit));
}
app->run(*window);
}
delete window;
return 0;
}
static void quit() {
if(window) window->hide(); //hide() will cause main::run() to end.
}
static void update() {
textview->set_buffer(text);
}
You start with
Gtk::TextView* textview = 0;
Later you do:
textview->set_buffer(text);
Maybe I missed something but at no point I see you point textview at an actual textview object. I would expect something like:
refBuilder->get_widget("???", textview );
during initialization.
Also you should use nullptr
instead of 0. Or NULL
assuming you do not use c++11