Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
Kevin Tony Avatar asked Oct 15 '25 13:10

Kevin Tony


2 Answers

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);
like image 126
David Ranieri Avatar answered Oct 18 '25 11:10

David Ranieri


The easiest way is to switch to a GtkSpinButton widget. This will allow you to set numeric only. Then you can set the range of values the user can use.

like image 33
theGtknerd Avatar answered Oct 18 '25 10:10

theGtknerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!