Important: Please read the 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
    class MainWindow : public QMainWindow

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

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

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    QValidator *validator = new QIntValidator(100, 999, this);

    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