File indexing completed on 2024-04-21 05:51:37
0001 /* 0002 * SPDX-FileCopyrightText: 2002-2003 Jesper K. Pedersen <blackie@kde.org> 0003 * 0004 * SPDX-License-Identifier: LGPL-2.0-only 0005 **/ 0006 0007 #include "limitedcharlineedit.h" 0008 0009 #include <QKeyEvent> 0010 #include <QValidator> 0011 #include <qregularexpression.h> 0012 0013 /** 0014 @internal 0015 A Validator for the @ref LimitedCharLineEdit 0016 */ 0017 class Validator : public QValidator 0018 { 0019 public: 0020 Validator(LimitedCharLineEdit::Mode mode, QWidget *parent) 0021 : QValidator(parent) 0022 , _mode(mode) 0023 { 0024 setObjectName(QStringLiteral("Validator")); 0025 } 0026 0027 QValidator::State validate(QString &txt, int & /*pos*/) const override 0028 { 0029 if (_mode == LimitedCharLineEdit::NORMAL 0030 || (_mode == LimitedCharLineEdit::HEX && txt.indexOf(QRegularExpression(QStringLiteral("^[0-9A-Fa-f]*$"))) != -1) 0031 || (_mode == LimitedCharLineEdit::OCT && txt.indexOf(QRegularExpression(QStringLiteral("^[0-7]*$"))) != -1)) { 0032 return QValidator::Acceptable; 0033 } else { 0034 return QValidator::Invalid; 0035 } 0036 } 0037 0038 private: 0039 LimitedCharLineEdit::Mode _mode; 0040 }; 0041 0042 void LimitedCharLineEdit::keyPressEvent(QKeyEvent *event) 0043 { 0044 QLineEdit::keyPressEvent(event); 0045 if (text().length() == _count && !event->text().isNull()) { 0046 focusNextPrevChild(true); 0047 } 0048 } 0049 0050 LimitedCharLineEdit::LimitedCharLineEdit(Mode mode, QWidget *parent, const QString &name) 0051 : QLineEdit(parent) 0052 { 0053 setObjectName(name); 0054 0055 if (mode == NORMAL) { 0056 _count = 1; 0057 } else if (mode == HEX) { 0058 _count = 4; 0059 } else { 0060 _count = 4; 0061 } 0062 0063 setMaxLength(_count); 0064 setFixedSize(fontMetrics().boundingRect(QLatin1Char('A')).width() * 5 + 5, sizeHint().height()); 0065 0066 setValidator(new Validator(mode, this)); 0067 }