From 5a3392db48b3c001ff504be997f1938b8813cb96 Mon Sep 17 00:00:00 2001 From: cristian64 Date: Fri, 7 Jun 2024 23:41:31 +0100 Subject: [PATCH] Relax input acceptance criteria in `AddressInputWidget`. The max length (previously `10`) has been lifted, and the input is now self-corrected as the user enters text: - Invalid characters are removed from the input. - The optional `0x` prefix is removed. - Any excess beyond the 8th character is removed. For example, this now allows the user to paste an address that may contain spaces, which is a fairly common case (e.g. `80 12 34 56`). --- Source/GUI/Widgets/AddressInputWidget.cpp | 32 ++++++++++++++++++----- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/Source/GUI/Widgets/AddressInputWidget.cpp b/Source/GUI/Widgets/AddressInputWidget.cpp index 07dab6d..b5fee93 100644 --- a/Source/GUI/Widgets/AddressInputWidget.cpp +++ b/Source/GUI/Widgets/AddressInputWidget.cpp @@ -15,15 +15,36 @@ class AddressValidator : public QValidator public: QValidator::State validate(QString& input, int& pos) const override { - if (input.startsWith("0x")) + // Strip invalid characters. { - input.remove(0, 2); - pos -= 2; + const QString copy{input}; + input.clear(); + for (qsizetype i{0}; i < copy.size(); ++i) + { + const QChar c{copy[i].toLower()}; + if (('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || c == 'x') + { + input.append(copy[i]); + continue; + } + if (i < pos) + { + pos -= 1; + } + } } - if (input.size() > 8) + + // Drop the optional prefix. + if (input.startsWith("0x")) { - return QValidator::Invalid; + input.remove(0, 2); + pos = std::max(0, pos - 2); } + + // Drop excess. + input.truncate(8); + pos = std::min(8, pos); + return QValidator::Acceptable; } }; @@ -33,7 +54,6 @@ AddressInputWidget::AddressInputWidget(QWidget* const parent) : QLineEdit(parent { setPlaceholderText("00000000"); setValidator(new AddressValidator); - setMaxLength(10); // 8 + 2, to allow the user to paste a value that includes the "0x" prefix const QFont fixedFont{QFontDatabase::systemFont(QFontDatabase::SystemFont::FixedFont)}; setFont(fixedFont);