comboboxex.cpp
1 //------------------------------------------------------------------------------
2 // comboboxex.cpp
3 //------------------------------------------------------------------------------
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 // 02110-1301 USA
19 //
20 //------------------------------------------------------------------------------
21 // Copyright (C) 2014 "Zalewa" <zalewapl@gmail.com>
22 //------------------------------------------------------------------------------
23 #include "comboboxex.h"
24 
25 #include <QLineEdit>
26 
27 ComboBoxEx::ComboBoxEx(QComboBox &comboBox)
28  : box(comboBox)
29 {
30 }
31 
32 QStringList ComboBoxEx::allItems() const
33 {
34  QStringList items;
35  for (int i = 0; i < box.count(); ++i)
36  items << box.itemText(i);
37  return items;
38 }
39 
40 bool ComboBoxEx::caseInsensitiveLessThan(const QString &s1, const QString &s2)
41 {
42  return s1.toLower() < s2.toLower();
43 }
44 
46 {
47  return removeItem(box.currentText());
48 }
49 
50 bool ComboBoxEx::removeItem(const QString &item)
51 {
52  int idx = box.findText(item);
53  if (idx >= 0)
54  {
55  // Simply removing current index won't give proper results
56  // if user edits the contents of the combo box.
57  box.removeItem(idx);
58  }
59  return idx >= 0;
60 }
61 
62 void ComboBoxEx::setCurrentOrAddNewAndSelect(const QString &item)
63 {
64  int idx = box.findText(item);
65  if (idx >= 0)
66  box.setCurrentIndex(idx);
67  else
68  {
69  box.insertItem(0, item);
70  box.setCurrentIndex(0);
71  }
72  box.lineEdit()->selectAll();
73 }
74 
75 void ComboBoxEx::setItemsSorted(QStringList items)
76 {
77  std::sort(items.begin(), items.end(), caseInsensitiveLessThan);
78  box.clear();
79  for (const QString &item : items)
80  {
81  if (box.findText(item) < 0)
82  box.addItem(item);
83  }
84 }
bool removeCurrentItem()
Removes currently selected item.
Definition: comboboxex.cpp:45
bool removeItem(const QString &item)
Removes item that matches specified one.
Definition: comboboxex.cpp:50