如何从gtk条目小部件中获取文本,然后将其转换为整数值。请注意,在我的代码中,我包含了一个名为Window的包装结构,它包含指向小部件的指针。总的来说,我声明了一个Window实例,然后用适当的GTK函数调用构建正确的小部件。然后,我将该窗口对象传递给处理单击操作的函数。然后我想以整数格式计算分子除以分母。下面是我的尝试。除了button_clicked函数外,所有代码都能工作。有什么想法吗?
#include <gtk/gtk.h>
#include <stdlib.h>
struct Window
{
GtkWidget *numerator;
GtkWidget *denominator;
GtkWidget *button;
GtkWidget *label;
};
void button_clicked(GtkWidget *widget, gpointer data)
{
Window* w = (Window*)data;
char buf[10];
char buffer[200];
GtkEntry* e = (GtkEntry*)w->numerator;
const gchar* entry1 = gtk_entry_get_text(e);
char* test = (char*)gchar;
int r = atoi(test);
sprintf(buf,"%d",r);
GtkWidget *label = w->label;
gtk_label_set_text(GTK_LABEL(label), buf);
}
int main(int argc, char*argv[])
{
GtkWidget *window;
GtkWidget *table;
Window w;
//Set up my window
gtk_init(&argc,&argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Division");
gtk_window_set_default_size(GTK_WINDOW(window),500,500);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
//Create my table and add it to the window
table = gtk_table_new(4,2,FALSE);
gtk_container_add(GTK_CONTAINER(window),table);
//Create instances of all my widgets
w.numerator = gtk_entry_new();
w.denominator = gtk_entry_new();
w.button = gtk_button_new_with_label("Click");
w.label = gtk_label_new("result");
//Attack the widgets to the table
gtk_table_attach(GTK_TABLE(table), w.numerator,0,1,0,1,GTK_FILL,GTK_FILL,5,5);
gtk_table_attach(GTK_TABLE(table), w.denominator,0,1,1,2,GTK_FILL,GTK_FILL,5,5);
gtk_table_attach(GTK_TABLE(table), w.button,0,1,2,3,GTK_FILL,GTK_FILL,5,5);
gtk_table_attach(GTK_TABLE(table), w.label,0,1,3,4,GTK_FILL,GTK_FILL,5,5);
//attach the click action to with the button to invoke the button_clicked function
g_signal_connect(G_OBJECT(w.button),"clicked",G_CALLBACK(button_clicked),&w);
g_signal_connect_swapped(G_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),NULL);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
如果我看对了,在你的"测试代码"中,你所要做的就是将标签字符串设置为"w->numerator"的内容,对吧?
线路
char* test = (char*)gchar;
在我看来很可疑,甚至没有编译,看起来像是打字错误。将"gchar"更改为"entry1",它应该按照您的意愿进行操作。
不过,我有一个建议:使用GtkSpinButton而不是GtkEntry。它就像一个为数值创建的自定义条目,检索这样的条目要容易很多倍。