so.very.tired
so.very.tired

Reputation: 3086

Gtkmm application crashes when dereferencing window object

I am trying to create simple application with gtkmm but I'm having some problem.

Here's how it looks now:

enter image description here

Here's the code to generate it:


MyWindow.h:

#ifndef MYWINDOW_H_
#define MYWINDOW_H_
#include <gtkmm/window.h>
#include <gtkmm/frame.h>
#include "MyDrawingArea.h"

class MyWindow :public Gtk::Window {
public:
    MyWindow();
    virtual ~MyWindow() {}

private:
    MyDrawingArea drawing_area;
};

#endif /* MYWINDOW_H_ */

MyWindow.cpp:

#include "MyWindow.h"

MyWindow::MyWindow() : drawing_area("Drawing area") {
    set_title("My app");
    set_border_width(10);
    add(drawing_area);
    drawing_area.draw_stuff_in_area();


    show_all_children();
}

MyDrawingArea.h:

#ifndef MYDRAWINGAREA_H_
#define MYDRAWINGAREA_H_
#include <gtkmm/frame.h>
#include <gtkmm/drawingarea.h>

class MyDrawingArea : public Gtk::Frame {
public:
    MyDrawingArea(const Glib::ustring& title);
    virtual ~MyDrawingArea() {}
    void draw_stuff_in_area();

private:
    Gtk::DrawingArea area;
};

#endif /* MYDRAWINGAREA_H_ */

MyDrawingArea.cpp:

#include "MyDrawingArea.h"
#include <iostream>
#include <gtkmm/window.h>

MyDrawingArea::MyDrawingArea(const Glib::ustring& title) : Gtk::Frame(title) {

    set_border_width(20);
    add(area);

    area.set_size_request(300, 250);
}

void MyDrawingArea::draw_stuff_in_area() {

    Cairo::RefPtr<Cairo::Context> cr = area.get_window()->create_cairo_context(); // program crashes here!
    // draw stuff with 'cr' here...

}

As the comment suggests, the program crashes when I try to create a Cairo::Context, though I don't think the Cairo::Context creation is the problem: Every dereferencing to the object returned by my_area.get_window() crashes the program!

Anyone know what's causing the problem?

Upvotes: 1

Views: 281

Answers (1)

Quentin Huot-Marchand
Quentin Huot-Marchand

Reputation: 117

Hi did you check the return value of area.get_window() because documentation says

Returns the widget’s window if it is realized, 0 otherwise.

Upvotes: 1

Related Questions