1.代码说明
- GtkTable的创建与使用
- GtkGrid的创建与使用
- 主要函数说明
//Adds a widget to the grid.
void
gtk_grid_attach (GtkGrid *grid,
GtkWidget *child,
gint left,
gint top,
gint width,
gint height);
- 参数说明
子构件child
的位置由left
和top
的值决定,每个子构件,这里主要指网格中的每个按钮所占网格“cells”
的数量由width
和height
决定 .
grid
:a GtkGrid 网格部件
child
:the widget to add 网格中要添加的小部件
left
:the column number to attach the left side of child to 小部件左侧关联的列号
top
:the row number to attach the top side of child to 小部件顶部关联的行号
width
:the number of columns that child will span 小部件所占列的数量
height
:the number of rows that child will span 小部件所占行的数量
2.源码如下
//buttons with table/grid in window (calculator.c)
#include <gtk/gtk.h>
int main (int argc,char *argv[])
{
GtkWidget *window;
//GtkWidget *table;
GtkWidget *grid;
GtkWidget *button;
gchar *values[16]={"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0",".","=","+",};
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
//gtk_window_set_title (GTK_WINDOW (window), "Calculator in GtkTable");
gtk_window_set_title (GTK_WINDOW (window), "Calculator in GtkGrid");
gtk_window_set_default_size (GTK_WINDOW(window),260,180);
gtk_container_set_border_width (GTK_CONTAINER (window), 5);
gtk_window_set_position (GTK_WINDOW (window),GTK_WIN_POS_CENTER_ALWAYS);
//从gtk3.4开始,已放弃使用GtkTable,建议使用GtkGrid,但该小部件目前仍能使用
//table=gtk_table_new (4,4,TRUE);
//gtk_table_set_row_spacing (GTK_TABLE(table),4,2);
//gtk_table_set_col_spacing (GTK_TABLE(table),4,2);
grid=gtk_grid_new ();
gtk_grid_set_row_spacing (GTK_GRID(grid),2);
gtk_grid_set_column_spacing (GTK_GRID(grid),2);
gint pos=0;
for(gint i=0;i<4;i++)
for(gint j=0;j<4;j++)
{
button=gtk_button_new_with_label(values[pos]);
gtk_widget_set_hexpand (button, TRUE);
gtk_widget_set_vexpand (button, TRUE);
//gtk_table_attach_defaults (GTK_TABLE(table),button,j,j+1,i,i+1);
gtk_grid_attach(GTK_GRID(grid),button,i,j,1,1);
pos++;
}
g_signal_connect (G_OBJECT (window), "destroy",
G_CALLBACK (gtk_main_quit), G_OBJECT(window));
//gtk_container_add (GTK_CONTAINER (window), table);
gtk_container_add (GTK_CONTAINER (window), grid);
gtk_widget_show_all(window);
gtk_main ();
return 0;
}
3.运行结果