Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to add QIntValidator to QLineEdit in designer [Solved]



  • Hi, I am learning QT4 with the book of QT4 of Daniel Molkentin.
    For so far, I have learned to use a validator with a LineEdit. It was pretty easy to add this in the source code file. But now I am learning to make a Dialog with the designer. Is it possible to add in the designer a validator for the LineEdit, for example to restrict input from 0 to 255.
    The problem I see, is I can add it later to the generated ui_xxxx.h file and that works fine, but when I make a change to the dialog with the designer, the file will be regenerate and my added code is gone.
    I hope there's a solution for this.



  • Welcome to DevNet.

    I think imputMask field in the properties list will create a validator.
    Or you can modify lineEdit through ui pointer of a mainwindow or widget.



  • Here is an example of how to modify generated UI from your code
    If you generated your initial main window using new project wizard then you will get the MainWindow class that has a pointer to generated ui
    MainWindow.h
    @
    class MainWindow : public QMainWindow
    {
    Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private:
        Ui::MainWindow *ui;
    

    };
    @
    then in your cpp file add a validator
    MainWindow.cpp
    @
    #include "MainWindow.h"
    #include "ui_MainWindow.h"

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    QValidator *validator = new QIntValidator(100, 999, this);
    ui->lineEdit->setValidator(validator);
    }

    MainWindow::~MainWindow()
    {
    delete ui;
    }
    @

    Just don't forget to modify lineEdit in MainWindow.cpp if you will change the name of QLineEdit object in a designer.



  • Thank you, the solution was indeed inheritance!



  • Glad it works.
    Please add [SOLVED] to the title of your message.


Log in to reply