Although the Qt Docs explicitly say that we shall "use masks together with validators" if we want range control in out QLineEdits
, this seems to be not that trivial. At least other people has similar problems. But mybe this helps:
Subclass the QLineEdit
and override focusInEvent()
and setValidator()
as follows:
----------------- mylineedit.h ----------------------
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QLineEdit>
#include <QFocusEvent>
#include <QRegExpValidator>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
private:
const QValidator *validator;
public:
MyLineEdit(QWidget *parent = 0);
void setValidator(const QValidator *v);
protected:
void focusInEvent(QFocusEvent *e);
};
#endif // MYLINEEDIT_H
------------------- mylineedit.cpp -------------------
#include "mylineedit.h"
MyLineEdit::MyLineEdit(QWidget *parent): QLineEdit(parent)
{
}
void MyLineEdit::setValidator(const QValidator *v)
{
validator = v;
QLineEdit::setValidator(v);
}
void MyLineEdit::focusInEvent(QFocusEvent *e)
{
Q_UNUSED(e);
clear();
setInputMask("");
setValidator(validator);
}
For the MyLineEdit
object itself we use a QRegExp
to allow only to enter time in 12 hour format without a colon at this point: 1152 e.g. When the user ends editing the lineedit gets an InpuMask of the form "HH:HH"
which makes 1152 to 11:52. The focus is cleared. If the user focuses again to the lineedit, it is cleared and the QRegExp
is set again and the user enteres the new time 1245 e.g. and so on...
--------------------- rootwindow.h --------------------
#ifndef ROOTWINDOW_H
#define ROOTWINDOW_H
#include "mylineedit.h"
#include <QMainWindow>
#include <QWidget>
#include <QtDebug>
class RootWindow : public QMainWindow
{
Q_OBJECT
private:
QWidget *widgetCentral;
MyLineEdit *line;
public:
RootWindow(QWidget *parent = 0);
~RootWindow();
private slots:
void slotLineEdited();
};
#endif // ROOTWINDOW_H
-------------- rootwindow.cpp ----------------------
#include "rootwindow.h"
RootWindow::RootWindow(QWidget *parent): QMainWindow(parent)
{
setCentralWidget(widgetCentral = new QWidget);
line = new MyLineEdit(widgetCentral);
line->setValidator(new QRegExpValidator( QRegExp("[0][0-9][0-5][0-9]|[1][0-2][0-5][0-9]") ));
connect(line, SIGNAL(editingFinished()), this, SLOT(slotLineEdited()));
}
RootWindow::~RootWindow()
{
}
void RootWindow::slotLineEdited()
{
line->setInputMask("HH:HH");
line->clearFocus();
}
---------------------- main.cpp --------------------------
#include "rootwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
RootWindow w;
w.show();
return a.exec();
}
It seems a little over the top but actually it is not that much new code and you do not need a colon key on your keyboard.