1

我有一个行编辑,用户必须以 12 小时时间格式输入。这是一个基于触摸的应用程序,我有自己的键盘,而这个键盘没有“:”(冒号)字符。因此,我为此目的使用了输入掩码。但我只有一个setInputMask( 99:99 )选项允许用户输入任何数字,而我必须将用户限制为 12 小时格式。

我使用 QRegexp 浏览了一些示例,但我不能像输入掩码中那样使用“:”。谁能指点我如何实施?

4

1 回答 1

0

尽管 Qt Docs 明确表示如果我们想要范围控制 in out ,我们将“将掩码与验证器一起使用” QLineEdits,但这似乎并不是那么微不足道。至少其他人也有类似的问题。但这有帮助:

子类化QLineEdit和覆盖focusInEvent()setValidator()如下:

----------------- 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);
}

对于MyLineEdit对象本身,我们使用 aQRegExp来只允许在此时输入不带冒号的 12 小时格式的时间:1152 例如,当用户结束编辑时,lineedit 会得到一个格式为"HH:HH"1152 到 11:52 的 InpuMask。焦点被清除。如果用户再次关注 lineedit,它会被清除并QRegExp再次设置,并且用户输入新的时间 1245 例如等等......

--------------------- 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();
}

它看起来有点过头了,但实际上它并没有那么多新代码,而且您不需要键盘上的冒号键。

于 2016-03-31T08:04:28.243 回答