Evgenii Legotckoi
Evgenii LegotckoiNov. 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.

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void onGetMaximumValuePushButtonClicked();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include "ui_Widget.h"

#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->getMaximumValuePushButton, &QPushButton::clicked, this, &Widget::onGetMaximumValuePushButtonClicked);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onGetMaximumValuePushButtonClicked()
{
    // Create a vector from all input fields you want to check
    std::vector<QLineEdit*> lineEdits = {ui->lineEdit_1, ui->lineEdit_2, ui->lineEdit_3, ui->lineEdit_4};
    // Create a vector to save values from input fields.
    std::vector<double> values;

    // We will try to get the values from all the input fields, if the text in them can be converted into a number
    for (const QLineEdit* lineEdit : lineEdits)
    {
        bool ok = false;
        double value = lineEdit->text().toDouble(&ok);
        if (ok)
        {
            values.push_back(value);
        }
    }

    // If numbers were not found
    if (values.empty())
    {
        // Then we set the value Nan in the result field.
        ui->resultlLineEdit->setText("Nan");
    }
    else
    {
        // Otherwise, we are trying to find the maximum value using the standard library.
        double max = *std::max_element(values.begin(), values.end());
        ui->resultlLineEdit->setText(QString::number(max));
    }
}

Git repository

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

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
ДЛ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
СЦ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
AT

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
J
JonnyJoMarch 30, 2023, 11:57 a.m.
Qt/C++ - Lesson 021. The drawing mouse in Qt Евгений, здравствуйте! Только начал изучение Qt и возник вопрос по 21ому уроку. После написания кода, выдаёт следующие ошибки В чём может быть проблема?
АН
Алексей НиколаевMarch 26, 2023, 9:10 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 9:04 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 24, 2023, 2:35 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 10:09 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
Now discuss on the forum
BlinCT
BlinCTApril 1, 2023, 5:16 a.m.
Нужен совет по работе с ListView и несколькими моделями Спасибо, сейчас займусь этим.
NSProject
NSProjectMarch 31, 2023, 2:55 a.m.
Проверка комментария принадлежит он пользователю или нет DRF (Django Rest Framework) Здравствуйте! Сегодня я столкнулся с такой проблеммой. Существует модель комметариев. Где их соответственно достаточное количество. Все они выводятся при помощи запроса ajax (axios). Так ка…
P
PisychMarch 30, 2023, 2:50 a.m.
Как подсчитать количество по условию? Да! Вот так работает! Огромное Вам спасибо! ........
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 29, 2023, 3:17 p.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.

Follow us in social networks