How to draw a subclassed DrawingArea widget?

I want to implement custom widgets by subclassing DrawingArea Widget, for that I need to draw with cairo. It looks like gtk3 has a new signal called "draw". How do I draw inside a widget? Should you redefine the map and implement signals?

A simple example code would be very helpful. Thank.

+3


source to share


1 answer


Simply put, you need to override the paint signal that will provide the Cairo context:

gboolean
user_function (GtkWidget    *widget,
               CairoContext *cr,
               gpointer      user_data)

      

Then you can use CairoContext cr

to paint the actual content of the widget.

From API C:

The GtkDrawingArea widget is used to create user interface elements. Its an essentially empty widget; you can paint it. After creating the drawing area, the application may want to connect to:

The mouse and buttons press signals to respond to input from the user. (Using gtk_widget_add_events () to enable the events you want to receive.)

  • The "implement" signal takes whatever action is needed when the widget is created on a particular display. (Create GDK resources in response to this signal.)

  • Size-allocate signal to take any necessary action when the widget is resized.

  • The "draw" signal to handle the redrawing of the widget's content.

The widget needs to digitize some draws when the widget changes, for example when distributing the size, you should use gtk_widget_queue_draw

to force the widget to draw itsef again.



Example. Using the drawing area not as a sub-class, but the concept remains: (taken from the Gnome C API )

gboolean
draw_callback (GtkWidget *widget, cairo_t *cr, gpointer data)
{
  guint width, height;
  GdkRGBA color;
  GtkStyleContext *context;

  context = gtk_widget_get_style_context (widget);

  width = gtk_widget_get_allocated_width (widget);
  height = gtk_widget_get_allocated_height (widget);

  gtk_render_background (context, cr, 0, 0, width, height);

  cairo_arc (cr,
             width / 2.0, height / 2.0,
             MIN (width, height) / 2.0,
             0, 2 * G_PI);

  gtk_style_context_get_color (context,
                               gtk_style_context_get_state (context),
                               &color);
  gdk_cairo_set_source_rgba (cr, &color);

  cairo_fill (cr);

 return FALSE;
}
[...]
  GtkWidget *drawing_area = gtk_drawing_area_new ();
  gtk_widget_set_size_request (drawing_area, 100, 100);
  g_signal_connect (G_OBJECT (drawing_area), "draw",
                    G_CALLBACK (draw_callback), NULL);

      

You should also read the section "Controlling Geometry Height for Width" in GtkWidget

I used C because there was no programming language reference to your question and at the same time it is the original API from which all the others are written.

There are several examples of creating Gtk + custom widgets on the web.

+4


source







All Articles