How to set Input Mask and QValidator to a QLineEdit at a time in Qt?

pyqt5 qlineedit default text
qlineedit::clear text
qlineedit::password
pyqt qlineedit validator example
qlineedit set alignment
qt text box
qlineedit get text
qlineedit ellipsis

I want a line edit which accepts an ip address. If I give input mask as:

ui->lineEdit->setInputMask("000.000.000.000");

It is accepting values greater than 255. If I give a validator then we have to give a dot(.) after every three digits. What would the best way to handle it?


How to set Input Mask and QValidator to a QLineEdit at a time in Qt?, It is accepting value greater than 255. Absolutely, because '0' means this: ASCII digit permitted but not required. As you can see, this is not your cup of tea. Qt; QTBUG-1644; Setting the input mask on a QLineEdit before setting QValidator makes the QLineEdit block input. Log In. But setting the input mask first then the


Hi I had almost the same problem. Solutions with inputmask or regExp were unsatisfactory. I decided to make my own bicycle.

Header:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLineEdit>
#include <QFrame>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindow *ui;
};

//=============================================================================
class CustomIpEditor : public QFrame
{
    Q_OBJECT
public:
    explicit CustomIpEditor(QWidget *parent = 0);
    virtual ~CustomIpEditor() {}
};

//=============================================================================
class CustomLineEdit : public QLineEdit
{
    Q_OBJECT
public:
    explicit CustomLineEdit(const QString & contents = "", QWidget *parent = 0);
    virtual ~CustomLineEdit() {}

signals:
    void jumpForward();
    void jumpBackward();

public slots:
    void jumpIn();

protected:
    virtual void focusInEvent(QFocusEvent *event);
    virtual void keyPressEvent(QKeyEvent * event);
    virtual void mouseReleaseEvent(QMouseEvent *event);

private:
    bool selectOnMouseRelease;
};

#endif // MAINWINDOW_H

Source:

#include <QVBoxLayout>
#include <QKeyEvent>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    centralWidget()->setLayout(new QVBoxLayout);

    CustomIpEditor *myed = new CustomIpEditor;
    centralWidget()->layout()->addWidget(myed);

}

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

//=============================================================================
CustomLineEdit::CustomLineEdit(const QString & contents, QWidget *parent) :
    QLineEdit(contents, parent), selectOnMouseRelease(false)
{
    QIntValidator *valid = new QIntValidator(0, 255, this);
    setValidator(valid);
}

void CustomLineEdit::jumpIn()
{
    setFocus();

    selectOnMouseRelease = false;
    selectAll();
}

void CustomLineEdit::focusInEvent(QFocusEvent *event)
{
    QLineEdit::focusInEvent(event);
    selectOnMouseRelease = true;
}

void CustomLineEdit::keyPressEvent(QKeyEvent * event)
{
    int key = event->key();
    int cursorPos = cursorPosition();

    // Jump forward by Space
    if (key == Qt::Key_Space) {
        emit jumpForward();
        event->accept();
        return;
    }

    // Jump Backward only from 0 cursor position
    if (cursorPos == 0) {
        if ((key == Qt::Key_Left) || (key == Qt::Key_Backspace)) {
            emit jumpBackward();
            event->accept();
            return;
        }
    }

    // Jump forward from last postion by right arrow
    if (cursorPos == text().count()) {
        if (key == Qt::Key_Right) {
            emit jumpForward();
            event->accept();
            return;
        }
    }

    // After key is placed cursor has new position
    QLineEdit::keyPressEvent(event);
    int freshCurPos = cursorPosition();

    if ((freshCurPos == 3) && (key != Qt::Key_Right))
        emit jumpForward();
}

void CustomLineEdit::mouseReleaseEvent(QMouseEvent *event)
{
    if(!selectOnMouseRelease)
        return;

    selectOnMouseRelease = false;
    selectAll();

    QLineEdit::mouseReleaseEvent(event);
}

//=============================================================================
void makeCommonStyle(QLineEdit* line) {
    line->setContentsMargins(0, 0, 0, 0);
    line->setAlignment(Qt::AlignCenter);
    line->setStyleSheet("QLineEdit { border: 0px none; }");
    line->setFrame(false);
    line->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
}

QLineEdit* makeIpSpliter() {
    QLineEdit *spliter = new QLineEdit(".");
    makeCommonStyle(spliter);

    spliter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    spliter->setMaximumWidth(10);
    spliter->setReadOnly(true);
    spliter->setFocusPolicy(Qt::NoFocus);
    return spliter;
}

CustomIpEditor::CustomIpEditor(QWidget *parent) :
    QFrame(parent)
{
    setContentsMargins(0, 0, 0, 0);
    setStyleSheet("QFrame { background-color: white;  border: 1px solid white; border-radius: 15px; }");

    QList <CustomLineEdit *>  lines;
    QList <CustomLineEdit *>::iterator linesIterator;

    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);
    lines.append(new CustomLineEdit);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->setSpacing(0);
    setLayout(mainLayout);

    for (linesIterator = lines.begin(); linesIterator != lines.end(); ++linesIterator) {
        makeCommonStyle(*linesIterator);
        mainLayout->addWidget(*linesIterator);

        if (*linesIterator != lines.last()) {
            connect(*linesIterator, &CustomLineEdit::jumpForward,
                    *(linesIterator+1), &CustomLineEdit::jumpIn);
            mainLayout->addWidget(makeIpSpliter());
        }
        if (*linesIterator != lines.first()) {
            connect(*linesIterator, &CustomLineEdit::jumpBackward,
                    *(linesIterator-1), &CustomLineEdit::jumpIn);
        }
    }

}

QLineEdit Class, I want a line edit which accepts an ip address. If I give input mask as: ui->lineEdit-​>setInputMask("000.000.000.000");. It is accepting values greater than 255. Qt's input masks and validators are two ways in which the programmer can control the data entered by the user and to check it for validity. When programming with widgets, both are available when using a QLineEdit widget. Input Masks. Lets look first at input masks. The QLineEdit [1] widget supports a property called inputMask. This is a string


The easier method is try inputmask option

ui->lineEdit_IP->setInputMask( "000.000.000.000" );

and in your validation code use the following simple condition

QHostAddress myIP;
   if( myIP.setAddress( ui->lineEdit_IP->text()) )
   qDebug()<<"Valid IP Address";
   else
   qDebug()<<"Invalid IP address";

Mixing QRegExpValidator and input mask and QLineEdit, Mixing QRegExpValidator and input mask and QLineEdit. I've set up a validator on a QLineEdit for entering a time interval: Qt Code: Switch view. Shows how to apply an input mask or validator to a QLineEdit widget to constrain accepted input values. Unit page at: http://tutorialcoding.com/qt/basic/unit015


For those who wonder about the following hint in the QT doku:

To get range control (e.g., for an IP address) use masks together with validators.

In this case the validator needs to take care of blanks. My solution, adapted from lpapp's answer and this Qt forum post, therefore reads:

QString ipRange = "(([ 0]+)|([ 0]*[0-9] *)|([0-9][0-9] )|([ 0][0-9][0-9])|(1[0-9][0-9])|([2][0-4][0-9])|(25[0-5]))";
// You may want to use QRegularExpression for new code with Qt 5 (not mandatory).
QRegExp ipRegex ("^" + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange
                 + "\\." + ipRange + "$");
QRegExpValidator *ipValidator = new QRegExpValidator(ipRegex, this);
lineEdit->setValidator(ipValidator);
lineEdit->setInputMask("000.000.000.000");
// Avoid having to move cursor before typing
linEdit->setCursorPosition(0);

I am a beginner at using regular expressions, so feel free to recommend improvements.

Qt Support for Input Masks and Validators, In the two-part Qt Basics, we'll look at Qt's support for input masks and validators. Today we The status of a validated string at a given time can be one of Invalid, To use a QValidator with a QLineEdit, you create a suitable  When removing the input mask in designer the code segment above code does work as it should. When using the input mask set in the code here, it has the same behaviour as with the input mask in the designer. Certainly I try to input only digits.


QLineEdit add-on: data filtering, validation and completion, I want a line edit which accepts an ip address. If I give input mask as: ui->lineEdit-​>setInputMask( I have a QLineEdit that a user is able to give input to using a keyboard. The line edit must only accept hexadecimal characters. The line edit must automatically put a delimiter character between every set of 2 hex characters The last delimiter character should be automatically removed when the user deletes the last hex characters.


Qt Tutorial: Unit 15, QLineEdit, Input-Masks and Validators, These are implemented by inputMask and QValidator , respectively. This is true most of the time, but the "set up" adjective is a very abstract  Set QLineEdit to accept only numbers. Ask Question See also the complete list of characters that can be used in an input mask. Set QLineEdit focus in Qt.


qt_widgets::QLineEdit - Rust, Returns a built-in Qt slot QLineEdit::setText that can be passed to qt_core::Signal​::connect . Note that if there is a validator() or inputMask() set on the line edit, the input follows the inputMask() and the validator() returns QValidator::​Acceptable. Calling update() several times normally results in just one paintEvent() call. This property holds the validation input mask. If no mask is set, inputMask() returns an empty string. Sets the QLineEdit's validation mask. Validators can be used instead of, or in conjunction with masks; see setValidator(). Unset the mask and return to normal QLineEdit operation by passing an empty string ("").