Search code examples
c++gtkmm

How to configure the widget Entry so that the length of the frame so as not to exceed 11 characters


I am on Ubuntu 20.04. I need to configure the frame of GTK::Entry widget to not exceed 11 characters. I thought I could use this code set_max_width_chars

Gtk::Entry nomUsb;
nomUsb.set_can_focus(true);
nomUsb.set_max_length(11);
nomUsb.set_max_width_chars(11);
boiteBoutonsH1.pack_start(nomUsb, Gtk::PACK_SHRINK);

but the result gives this (20 characters):

enter image description here

Any ideas ?


Solution

  • Here is some code that will, I suspect, do what you want:

    #include <gtkmm.h>
    
    class MainWindow : public Gtk::Window
    {
    
    public:
    
        MainWindow()
        {
            // Can't type in more than 11 chars (copy/paste will truncate):
            m_11CharMax.set_max_length(11);
    
            // Sets the width of the entry to about 11 characters wide (depends on the character):
            m_11CharMax.set_width_chars(11);
        
            add(m_11CharMax);
            show_all();
        }
    
    private:
    
        Gtk::Entry m_11CharMax;
    
    };
    
    int main(int argc, char **argv)
    {
        auto app = Gtk::Application::create(argc, argv, "so.question.q63568716");
        
        MainWindow w;
    
        return app->run(w);
    }
    

    The following Makefile will build this for you (assuming the code is in a file named main.cpp:

    all: main.cpp
        g++ main.cpp -o example.out `pkg-config gtkmm-3.0 --cflags --libs`
    

    The program example.out will create a window with a Gtk::Entry as its sole child widget. This entry will be about 11 characters wide (note that this depends on the character. For example, m is larger than l in the UI's font). Also, it will not accept more than 11 characters as input:

    enter image description here

    If you try to copy and paste more that 11 characters to it, the entry will automatically truncate it to fit. Even if you resize it, you will not be able to feed it more that 11 characters:

    enter image description here