1.代码说明
GNU GPL
的写法与使用- 小部件
button
及容器fixed
和window
的使用 - 随机数生成相关函数
g_rand_new ()
和g_rand_int_range()
的使用 click
事件自定义回调函数move_button
以及g_signal_connect()
的使用- 以上相关函数可安装
devhelp
进行离线查找
$ sudo apt install devhelp
2.源代码如下
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* movebuttons.c
* Copyright (C) 2023 jack <jack@jack-ThinkPad-L470>
*
* gtk-demos is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* gtk-demos is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//move buttons in a fixed area (movebuttons.c)
#include <gtk/gtk.h>
gint x=50;
gint y=50;
/* 随机生成小部件坐标,并更新Button的坐标信息(x,y). */
void
move_button (GtkWidget *widget,
GtkWidget *fixed,
GtkWidget *button)
{
GRand *gr=g_rand_new ();
x=g_rand_int_range (gr,30,300);
y=g_rand_int_range (gr,50,300);
gchar pos[20];
g_snprintf(pos,20,"Click me(%d,%d)",x,y);
gtk_button_set_label (G_OBJECT (button),pos);
gtk_fixed_move (GTK_FIXED(fixed),widget,x,y);
}
int main (int argc,char *argv[])
{
gint i;
GtkWidget *window, *fixed,*button;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Move Buttons in Fixed Container");
gtk_window_set_default_size (GTK_WINDOW(window),400,400);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_window_set_position (GTK_WINDOW (window),GTK_WIN_POS_CENTER_ALWAYS);
g_signal_connect (G_OBJECT (window), "destroy",
G_CALLBACK (gtk_main_quit), NULL);
gtk_container_set_border_width (GTK_CONTAINER(window),10);
fixed=gtk_fixed_new();
gtk_container_add (GTK_CONTAINER (window), fixed);
gtk_widget_show (fixed);
GRand *gr=g_rand_new ();
//生成三个Button,并连接click事件的回调函数move_button ()
for(i=1;i<=3;i++){
//生成20-300以及80-300之间的随机整数
gint rx=g_rand_int_range (gr,20,300);
gint ry=g_rand_int_range (gr,80,300);
gchar pos[20];
g_snprintf(pos,20,"Click me(%d,%d)",rx,ry);
//利用随机坐标生成Button的标签信息
button=gtk_button_new_with_label (pos);
g_signal_connect(G_OBJECT(button),"clicked",
G_CALLBACK(move_button),fixed);
gtk_fixed_put (GTK_FIXED(fixed),button,i+rx,i+ry);
gtk_widget_show (button);
}
gtk_widget_show(window);
gtk_main ();
return 0;
}
3.程序在Anjuta中运行的结果
movebuttons