Evgenii Legotckoi
Nov. 26, 2018, 4:11 a.m.

Qt/C++ Tutorial 087. Get the maximum number of multiple input fields QLineEdit

Напишем небольшое приложение для получения максимального числа из нескольких полей QLineEdit.

This means that we will have several QLineEdit fields, let's say 4 pieces into which numbers will be entered. And there will be the fifth field QLineEdit in which the result will be displayed. We also have a QPushButton button, by clicking we will get values from all QLineEdit fields and among them we will look for the maximum number that has been entered into these fields.

The application will look like this


The appearance of the application window was compiled in the interface designer. I will not elaborate on this point. You will be able to study the project in my Git repository in detail.

Widget.h

The class of the main application window. It will be defined slot handling button.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. namespace Ui {
  7. class Widget;
  8. }
  9.  
  10. class Widget : public QWidget
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit Widget(QWidget *parent = nullptr);
  16. ~Widget();
  17.  
  18. private slots:
  19. void onGetMaximumValuePushButtonClicked();
  20.  
  21. private:
  22. Ui::Widget *ui;
  23. };
  24.  
  25. #endif // WIDGET_H

Widget.cpp

  1. #include "Widget.h"
  2. #include "ui_Widget.h"
  3.  
  4. #include <QDebug>
  5.  
  6. Widget::Widget(QWidget *parent) :
  7. QWidget(parent),
  8. ui(new Ui::Widget)
  9. {
  10. ui->setupUi(this);
  11.  
  12. connect(ui->getMaximumValuePushButton, &QPushButton::clicked, this, &Widget::onGetMaximumValuePushButtonClicked);
  13. }
  14.  
  15. Widget::~Widget()
  16. {
  17. delete ui;
  18. }
  19.  
  20. void Widget::onGetMaximumValuePushButtonClicked()
  21. {
  22. // Create a vector from all input fields you want to check
  23. std::vector<QLineEdit*> lineEdits = {ui->lineEdit_1, ui->lineEdit_2, ui->lineEdit_3, ui->lineEdit_4};
  24. // Create a vector to save values from input fields.
  25. std::vector<double> values;
  26.  
  27. // We will try to get the values from all the input fields, if the text in them can be converted into a number
  28. for (const QLineEdit* lineEdit : lineEdits)
  29. {
  30. bool ok = false;
  31. double value = lineEdit->text().toDouble(&ok);
  32. if (ok)
  33. {
  34. values.push_back(value);
  35. }
  36. }
  37.  
  38. // If numbers were not found
  39. if (values.empty())
  40. {
  41. // Then we set the value Nan in the result field.
  42. ui->resultlLineEdit->setText("Nan");
  43. }
  44. else
  45. {
  46. // Otherwise, we are trying to find the maximum value using the standard library.
  47. double max = *std::max_element(values.begin(), values.end());
  48. ui->resultlLineEdit->setText(QString::number(max));
  49. }
  50. }

Git repository

And here is the link to the project itself in my Git repository .

Recommended articles on this topic

By article asked0question(s)

3

Do you like it? Share on social networks!

Taishel73
  • March 29, 2019, 2:10 a.m.

Что если необходимо найти максимальное значение из n-го количества полей ввода?

Evgenii Legotckoi
  • March 29, 2019, 6:27 p.m.

Всё тоже самое, добавить в вектор больше полей

Taishel73
  • March 30, 2019, 2:05 a.m.

Я имею в виду, что если количество полей будет задаваться в самой программе (пользователем), а не в коде

Evgenii Legotckoi
  • March 30, 2019, 3:08 a.m.

В данном случае пользователь будет автоматически добавлять поля, как я понимаю, в данном случае тогда можно будет создать и логику для автоматического маппинга имён полей в переменные и т.д. Это будет что-то подобное как в этом уроке по динамическому созданию виджетов , только несколько сложнее.

Будет создаваться вектор виджетов, из него будут забираться данные и посылаться на сравнение и т.д.

Taishel73
  • April 2, 2019, 12:59 a.m.

Понял. Спасибо)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup