Search code examples
c++gtkmm

Gtkmm 3.0: How to get user class data in on_draw method of DrawingArea


In my first Gtkmm 3.0 program, I’m having trouble with the program structure and getting access to my class data from a DrawingArea class.

Based on a demo program from the gnome website (“Drawing thin lines”), I have a window class, a drawingArea class and a Board class with user data.

A drawingArea object is defined as a member variable in the windows class. In the window class constructor, I instantiate a Board object.

Now I want to access Board member variables in the on_draw routine in the drawingArea class. What's the best way to do this?

My board class has:

class Board {
public:
   int sqPix;       

My window class has:

Board &ExampleWindow::getBd()   { return bdw; }
void  ExampleWindow::setBd(Board b) {bdw = b; }
ExampleWindow::ExampleWindow(char * fn, vector<int>& t)
{
  Board bd = Board(t);
  setBd(bd);

My window class .h file has:

 class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  ExampleWindow(char * fn, std::vector<int>& t);
  virtual ~ExampleWindow();
  Board &getBd();
  void  setBd(Board b);
private:
  Board bdw;
  MyArea m_Area;

In my drawing area class, I want to do something like:

bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
  Gtk::Allocation allocation = get_allocation();
  =====> int sqPix = ExampleWindow::getBd().sqPix;  

Solution

  • You should probably not couple your top level window to the drawing area, otherwise you can't reuse the drawing code in some other window of your application, for example, preferences to change an example board's appearance.

    Instead, pass a Board reference or pointer to your DrawingArea in its constructor. Here is the window's constructor where the DrawingArea takes a Board reference. You can use a pointer and setBoard() instead if you think a DrawingArea won't always be associated with one Board:

    ExampleWindow(const char * fn, const vector<int>& t) : bdw(t), m_Area(bdw) {
      ...
    }