gridgtkcairovaladrawingarea

Gtk.DrawingArea blank when attached to Gtk.Grid


(This is my first post, sorry if I do something wrong...)

I am writing a program in Vala with which one can design a classroom. I have decided to use GTK for the GUI (Vala integrates well with this), and Cairo to draw the classroom diagram (GTK comes with this by default).

I have created a 'classroom' class (a subclass of Gtk.DrawingArea), which currently should just display a square:

public class Classroom : DrawingArea
{
    private delegate void DrawMethod();

    public Classroom()
    {
        this.draw.connect((widget, context) => {
            return draw_class(widget, context, context.stroke);
            });
    }

    bool draw_class(Widget widget, Context context, DrawMethod draw_method)
    {
        context.set_source_rgb(0, 0, 0);
        context.set_line_width(8);
        context.set_line_join (LineJoin.ROUND);

        context.save();

        context.new_path();
        context.move_to(10, 10);
        context.line_to(30, 10);
        context.line_to(30, 30);
        context.line_to(10, 30);
        context.line_to(10, 10);
        context.close_path();

        draw_method();  // Actually draw the lines in the buffer to the widget

        context.restore();

        return true;
    }
}

I have also created a class for my application:

public class SeatingPlanApp : Gtk.Application
{
    protected override void activate ()
    {
        var root = new Gtk.ApplicationWindow(this);
        root.title = "Seating Plan";
        root.set_border_width(12);
        root.destroy.connect(Gtk.main_quit);

        var grid = new Gtk.Grid();
        root.add(grid);

        /* Make our classroom area */
        var classroom = new Classroom();
        grid.attach(classroom, 0, 0, 1, 1);
        //root.add(classroom);

        root.show_all();
    }

    public SeatingPlanApp()
    {
        Object(application_id : "com.github.albert-tomanek.SeatingPlan");
    }
}

And this is my main function:

int main (string[] args)
{
    return new SeatingPlanApp().run(args);
}

I put my classroom widget into a Gtk.Grid, my layout widget of choice. When I compile my code and run it, I get a blank window:

My blank window

However, if I do not use Gtk.Grid, and just add my classroom using root.add() (which I have commented out), the classroom widget is displayed correctly:

When it works, without using Gtk.Grid

Why does my widget not show up when adding it using Gtk.Grid?

What can I do to fix this?


Solution

  • The problem is that the cell is sized 0x0 pixels, because the grid doesn't know how much space your drawing area actually needs.

    A simple solution is to just request some fixed size, try this:

    var classroom = new Classroom();
    classroom.set_size_request (40, 40);
    

    PS: I got this idea by looking at other similar questions on SO, particularly this one.