问题
DrawingArea.hpp
#ifndef __DRAWINGAREA
#define __DRAWINGAREA
#include <gtkmm.h>
class DrawingArea : public Gtk::DrawingArea
{
public:
bool on_my_draw(const Cairo::RefPtr<Cairo::Context>& cr);
DrawingArea(GtkDrawingArea* &cobject, const Glib::RefPtr<Gtk::Builder>& builder);
};
#endif // __DRAWINGAREA
DrawingArea.cpp
#include "DrawingArea.hpp"
#include <iostream>
DrawingArea::DrawingArea(GtkDrawingArea* &cobject, const Glib::RefPtr<Gtk::Builder>& builder)
{
this->signal_draw().connect(sigc::mem_fun(this, &DrawingArea::on_my_draw));
}
bool DrawingArea::on_my_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
std::cout << "i am here" << std::endl;
}
Having compiled that into the application, I have tested that the DrawingArea
constructor does in fact get fired (I use get_widget_derived
to connect it to Glade, but that should not be important here).
I would expect to see "I am here"
when I start the application, or when it needs to redraw the DrawingArea
, but it doesn't happen for whatever reason.
Despite the fact that the area is already shown, I tried to fire up show_all_children
on the window that it's a part of, but this didn't help.
Now tried to add
To .hpp:
bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override;
And to .cpp:
bool DrawingArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
std::cout << "i am here!!!" << std::endl;
}
This didn't help.
Also have attempted to pass false
as the second parameter to connect()
, and that didn't help.
回答1:
It is simpler to just override the default handler - on_draw(), as in this simple example: https://developer.gnome.org/gtkmm-tutorial/stable/sec-cairo-drawing-lines.html.en#cairo-example-lines
These signals that return bool often have to be connected "before" in order for the extra signal handlers to be called: https://developer.gnome.org/gtkmm-tutorial/stable/sec-xeventsignals.html.en#signal-handler-sequence
回答2:
The problem was quite interesting, and rather different to what one may expect, so i'll post the answer that i got.
The issue was the i needed to initialise the object correctly. Specifically i was not calling the constructor of the superclass. I needed to do:
DrawingArea::DrawingArea(GtkDrawingArea* cobject, const Glib::RefPtr<Gtk::Builder>& builder)
: Gtk::DrawingArea(cobject) // <--- this is a very important bit
{
//...
}
Without that not only the signal connection was getting lost (which is understandable, since the whole part of the object that deals with calling of the needed functions was gone), but even the overridden on_draw
stopped working (and that's something i still do not understand).
来源:https://stackoverflow.com/questions/36554190/draw-signal-doesnt-get-fired-in-gtkmm-when-derived-class-doesnt-call-a-superc