Kstars

unitspinboxwidget.cpp
1/*
2 SPDX-FileCopyrightText: 2015 Utkarsh Simha <utkarshsimha@gmail.com>
3
4 SPDX-License-Identifier: GPL-2.0-or-later
5*/
6#include "unitspinboxwidget.h"
7#include<cmath>
8
9UnitSpinBoxWidget::UnitSpinBoxWidget(QWidget *parent) : QWidget(parent), ui(new Ui::UnitSpinBoxWidget)
10{
11 ui->setupUi(this);
12 doubleSpinBox = ui->doubleSpinBox;
13 comboBox = ui->comboBox;
14 //connect(spinBox, SIGNAL(valueChanged(int)), this, SLOT(setText()));
15 //connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setText()));
16}
17
18UnitSpinBoxWidget::~UnitSpinBoxWidget()
19{
20 delete ui;
21}
22
24{
26 qv.setValue(conversionFactor);
27 comboBox->addItem(unitName, qv);
28}
29
31{
32 int index = comboBox->currentIndex();
33 QVariant qv = comboBox->itemData(index);
34 double conversionFactor = qv.value<double>();
35 double value = doubleSpinBox->value();
36 return value * conversionFactor;
37}
38
39void UnitSpinBoxWidget::setValue(const double value)
40{
41 if (value < 1e-20 && value > -1e-20)
42 {
43 // Practically zero
44 doubleSpinBox->setValue(value);
45 return;
46 }
47 std::vector<double> diffs;
48 for (int index = 0; index < comboBox->count(); ++index)
49 {
50 QVariant qv = comboBox->itemData(index);
51 double conversionFactor = qv.value<double>();
52 diffs.push_back(std::abs(std::abs(value) / conversionFactor - 1.));
53 }
54 auto it = std::min_element(diffs.cbegin(), diffs.cend());
55 int index = std::distance(diffs.cbegin(), it);
56 comboBox->setCurrentIndex(index);
57 QVariant qv = comboBox->itemData(index);
58 double conversionFactor = qv.value<double>();
59 doubleSpinBox->setValue(value / conversionFactor);
60}
The UnitSpinBoxWidget class It is a widget that provides a DoubleSpinBox and a ComboBox for conversio...
double value() const
value Returns value upon conversion
void setValue(const double value)
Sets the given value.
void addUnit(const QString &unitName, double conversionFactor)
addUnit Adds a item to the combo box
void addItem(const QIcon &icon, const QString &text, const QVariant &userData)
QVariant itemData(int index, int role) const const
void setupUi(QWidget *widget)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri May 17 2024 11:48:27 by doxygen 1.10.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.