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  {
37  items << box.itemText(i);
38  }
39  return items;
40 }
41 
42 bool ComboBoxEx::caseInsensitiveLessThan(const QString &s1, const QString &s2)
43 {
44  return s1.toLower() < s2.toLower();
45 }
46 
48 {
49  return removeItem(box.currentText());
50 }
51 
52 bool ComboBoxEx::removeItem(const QString &item)
53 {
54  int idx = box.findText(item);
55  if (idx >= 0)
56  {
57  // Simply removing current index won't give proper results
58  // if user edits the contents of the combo box.
59  box.removeItem(idx);
60  }
61  return idx >= 0;
62 }
63 
64 void ComboBoxEx::setCurrentOrAddNewAndSelect(const QString &item)
65 {
66  int idx = box.findText(item);
67  if (idx >= 0)
68  {
69  box.setCurrentIndex(idx);
70  }
71  else
72  {
73  box.insertItem(0, item);
74  box.setCurrentIndex(0);
75  }
76  box.lineEdit()->selectAll();
77 }
78 
79 void ComboBoxEx::setItemsSorted(QStringList items)
80 {
81  qSort(items.begin(), items.end(), caseInsensitiveLessThan);
82  box.clear();
83  foreach (const QString& item, items)
84  {
85  if (box.findText(item) < 0)
86  {
87  box.addItem(item);
88  }
89  }
90 }
bool removeCurrentItem()
Removes currently selected item.
Definition: comboboxex.cpp:47
bool removeItem(const QString &item)
Removes item that matches specified one.
Definition: comboboxex.cpp:52