number_input.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "ui/widgets/fields/number_input.h"
  8. namespace Ui {
  9. NumberInput::NumberInput(
  10. QWidget *parent,
  11. const style::InputField &st,
  12. rpl::producer<QString> placeholder,
  13. const QString &value,
  14. int limit)
  15. : MaskedInputField(parent, st, std::move(placeholder), value)
  16. , _limit(limit) {
  17. if (!value.toInt() || (limit > 0 && value.toInt() > limit)) {
  18. setText(QString());
  19. }
  20. }
  21. void NumberInput::changeLimit(int limit) {
  22. _limit = limit;
  23. }
  24. void NumberInput::correctValue(
  25. const QString &was,
  26. int wasCursor,
  27. QString &now,
  28. int &nowCursor) {
  29. QString newText;
  30. newText.reserve(now.size());
  31. auto newPos = nowCursor;
  32. for (auto i = 0, l = int(now.size()); i < l; ++i) {
  33. if (now.at(i).isDigit()) {
  34. newText.append(now.at(i));
  35. } else if (i < nowCursor) {
  36. --newPos;
  37. }
  38. }
  39. if (!newText.toInt()) {
  40. newText = QString();
  41. newPos = 0;
  42. } else if (_limit > 0 && newText.toInt() > _limit) {
  43. newText = was;
  44. newPos = wasCursor;
  45. }
  46. setCorrectedText(now, nowCursor, newText, newPos);
  47. }
  48. } // namespace Ui