Gtk.jl clear canvas on key event

Hi! I’m trying to make a simple drawing app, and i want to clear the canvas when space is pressed. I understood from this discussion Resetting the canvas within Cairo.jl and Gtk.jl for an image selection viewing gui that you can just fill a rectangle over the canvas, but i can’t get it to work.

@guarded draw(c) do widget
    ctx = getgc(c)
    h = height(c)
    w = width(c)
    # Paint red rectangle
    for (xs,ys) in zip(xss,yss)
        for ((x0,y0),(x1,y1)) in zip(zip(xs[1:end-1],ys[1:end-1]),zip(xs[2:end],ys[2:end]))
            set_source_rgb(ctx,1, 0, 0)
            move_to(ctx,x0,y0)
            line_to(ctx,x1,y1)
            stroke(ctx)
        end
    end
end


signal_connect(win,"key_press_event") do widget, event
    # SPACE
    if event.keyval == 32
        
        ctx = getgc(c)
        set_source_rgb(ctx, 1, 0, 0)
        rectangle(ctx,0,0,600,600)
        stroke(ctx)
    end
end

Solved it! I needed to make the rectangle inside the draw function, then call it from the key event:

@guarded draw(c) do widget
    ctx = getgc(c)
    h = height(c)
    w = width(c)
    # Paint red rectangle
    set_source_rgb(ctx,1,1,1)
    rectangle(ctx,0,0,600,600)
    fill(ctx)
    for (xs,ys) in zip(xss,yss)
        for ((x0,y0),(x1,y1)) in zip(zip(xs[1:end-1],ys[1:end-1]),zip(xs[2:end],ys[2:end]))
            set_source_rgb(ctx,1, 0, 0)
            move_to(ctx,x0,y0)
            line_to(ctx,x1,y1)
            stroke(ctx)
        end
    end
end

signal_connect(win,"key_press_event") do widget, event
    # SPACE
    if event.keyval == 32
        empty!(xss)
        empty!(yss)
        draw(c)
    end
end
1 Like

I also realized now you can do the overwrite directly in the keycode function as long as you use reveal() at the end:

    elseif event.keyval == 122
        println(" (z was pressed)")
        ctx = getgc(c)
        set_source_rgb(ctx,1,1,1)
        rectangle(ctx,0,0,600,600)
        fill(ctx)
        reveal(c)
    end