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. -
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_OBJECTpublic: 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.