File indexing completed on 2024-12-15 04:54:44

0001 /******************************************************************************
0002  *
0003  *  SPDX-FileCopyrightText: 2008 Szymon Tomasz Stefanek <pragma@kvirc.net>
0004  *
0005  *  SPDX-License-Identifier: GPL-2.0-or-later
0006  *
0007  *******************************************************************************/
0008 
0009 #include "utils/comboboxutils.h"
0010 
0011 #include <QVariant>
0012 
0013 #include <QComboBox>
0014 
0015 using namespace MessageList::Utils;
0016 
0017 void ComboBoxUtils::fillIntegerOptionCombo(QComboBox *combo, const QList<QPair<QString, int>> &optionDescriptors)
0018 {
0019     int val = getIntegerOptionComboValue(combo, -1);
0020     combo->clear();
0021     int valIdx = -1;
0022     int idx = 0;
0023 
0024     QList<QPair<QString, int>>::ConstIterator end(optionDescriptors.end());
0025 
0026     for (QList<QPair<QString, int>>::ConstIterator it = optionDescriptors.constBegin(); it != end; ++it) {
0027         if (val == (*it).second) {
0028             valIdx = idx;
0029         }
0030         combo->addItem((*it).first, QVariant((*it).second));
0031         ++idx;
0032     }
0033     if (idx == 0) {
0034         combo->addItem(QStringLiteral("-"), QVariant((int)0)); // always default to 0
0035         combo->setEnabled(false);
0036     } else {
0037         if (!combo->isEnabled()) {
0038             combo->setEnabled(true);
0039         }
0040         if (valIdx >= 0) {
0041             combo->setCurrentIndex(valIdx);
0042         }
0043         if (combo->count() == 1) {
0044             combo->setEnabled(false); // disable when there is no choice
0045         }
0046     }
0047 }
0048 
0049 void ComboBoxUtils::setIntegerOptionComboValue(QComboBox *combo, int value)
0050 {
0051     if (combo->itemData(combo->currentIndex()).toInt() == value) {
0052         return;
0053     }
0054     int index = combo->findData(value);
0055     if (index != -1) {
0056         combo->setCurrentIndex(index);
0057     } else {
0058         combo->setCurrentIndex(0); // default
0059     }
0060 }
0061 
0062 int ComboBoxUtils::getIntegerOptionComboValue(QComboBox *combo, int defaultValue)
0063 {
0064     const int idx = combo->currentIndex();
0065     if (idx < 0) {
0066         return defaultValue;
0067     }
0068 
0069     QVariant data = combo->itemData(idx);
0070     bool ok;
0071     const int val = data.toInt(&ok);
0072     if (!ok) {
0073         return defaultValue;
0074     }
0075     return val;
0076 }