cuser-interfaceubuntugtkgtk3

How to set GtkEntry widget to only accept numbers using C?


I'm trying to get a 4 digit input from the user but a non numeric entry is not acceptable. Instead of checking for non numeric values, can I allow the user to only enter numeric values into the GtkEntry box?

GtkWidget *entry_pin;
entry_pin=gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY(entry_pin),4);

By the way I'm running on Ubuntu.


Solution

  • Antoher way is stopping the emission in a callback

    #include <ctype.h>
    
    void insert_text_event(GtkEditable *editable, const gchar *text, gint length, gint *position, gpointer data)
    {
        int i;
    
        for (i = 0; i < length; i++) {
            if (!isdigit(text[i])) {
                g_signal_stop_emission_by_name(G_OBJECT(editable), "insert-text");
                return;
            }
        }
    }
    

    The callback can be set as:

    g_signal_connect(G_OBJECT(widget), "insert-text", G_CALLBACK(insert_text_event), NULL);