Questions about C language

Asked 2 years ago, Updated 2 years ago, 91 views

#include<gtk/gtk.h>
# include <math.h>

gboolean redraw (GtkWidget*w, gpointer user_data);
gboolean draw (GtkWidget*w, gpointer user_data);

int main (int argc, char**argv)
{
  GtkWidget*win, *l1, *l2, *l3, *l4, *vbox, *hbox, *b1, *b2;
  gtk_init(&argc,&argv);

  /* make a window*/
  win=gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(win, "destroy", gtk_main_quit, NULL);

  /* make a label, make a drawing area*/
  l1 = gtk_label_new("New");
  l2 = gtk_drawing_area_new();
  l3 =gtk_label_new("Redraw");
  l4 = gtk_label_new("EXIT");

  /*make a button*/
  b1=gtk_button_new();
  b2=gtk_button_new();

  /* make a vbox*/
  vbox=gtk_vbox_new(FALSE,0);
  gtk_container_add(GTK_CONTAINER(win), vbox);
  gtk_box_pack_start(GTK_BOX(vbox), l1, TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), l2, TRUE, TRUE, 0);
  g_signal_connect(l2, "expose_event", G_CALLBACK(draw), NULL);
  gtk_widget_set_size_request(l2,400,200);

  /* make a hbox*/
  hbox=gtk_hbox_new(TRUE,0);
  gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 0);

  gtk_box_pack_start(GTK_BOX(hbox), b2, TRUE, TRUE, 0);
  g_signal_connect(b2, "clicked", G_CALLBACK(redraw), NULL);
  gtk_container_add(GTK_CONTAINER(b2),l3);

  gtk_box_pack_start(GTK_BOX(hbox), b1, TRUE, TRUE, 0);
  g_signal_connect(b1, "clicked", gtk_main_quit, NULL);
  gtk_container_add(GTK_CONTAINER(b1),l4);

  gtk_widget_show_all(win);

  gtk_main();

  return 0;
}

gboolean redraw (GtkWidget*w, gpointer user_data)
{ 
}

gboolean draw (GtkWidget*w, gpointer user_data) 
{
  gdk_draw_rectangle(w->window, w->style->fg_gc [GTK_WIDGET_STATE(w)],
         TRUE, 100, 50, 200, 100);

  return TRUE;
}

I'd like to write a program in the redraw function where the drawing in the center disappears or appears when I press the Redraw button, but I can't think of any ideas.Could someone please help me?

c gtk

2022-09-30 20:50

1 Answers

First, pass the drawing area l2 to the parameter of clicked in redraw.

g_signal_connect(b2, "clicked", G_CALLBACK(redraw), l2);

Then toggle the static variable in the event handler to show or hide the drawing area according to its state.

gboolean redraw (GtkWidget*w, gpointer user_data)
{ 
  static int visible = 1;
  GtkWidget*l2=(GtkWidget*)user_data;
  visible=!visible;

  if (visible)
    gtk_widget_show(l2);
  else
    gtk_widget_hide(l2);
  return TRUE;
}


2022-09-30 20:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.