]> sigrok.org Git - pulseview.git/blame_incremental - pv/prop/enum.cpp
Enum: Use an iterator instead of iterating by indexes
[pulseview.git] / pv / prop / enum.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <assert.h>
22
23#include <QComboBox>
24
25#include "enum.h"
26
27using std::pair;
28using std::vector;
29
30namespace pv {
31namespace prop {
32
33Enum::Enum(QString name,
34 vector<pair<GVariant*, QString> > values,
35 Getter getter, Setter setter) :
36 Property(name, getter, setter),
37 _values(values),
38 _selector(NULL)
39{
40}
41
42Enum::~Enum()
43{
44 for (vector< pair<GVariant*, QString> >::const_iterator i =
45 _values.begin(); i != _values.end(); i++)
46 g_variant_unref((*i).first);
47}
48
49QWidget* Enum::get_widget(QWidget *parent, bool auto_commit)
50{
51 if (_selector)
52 return _selector;
53
54 GVariant *const value = _getter ? _getter() : NULL;
55 if (!value)
56 return NULL;
57
58 _selector = new QComboBox(parent);
59 for (unsigned int i = 0; i < _values.size(); i++) {
60 const pair<GVariant*, QString> &v = _values[i];
61 _selector->addItem(v.second, qVariantFromValue((void*)v.first));
62 if (value && g_variant_equal(v.first, value))
63 _selector->setCurrentIndex(i);
64 }
65
66 g_variant_unref(value);
67
68 if (auto_commit)
69 connect(_selector, SIGNAL(currentIndexChanged(int)),
70 this, SLOT(on_current_item_changed(int)));
71
72 return _selector;
73}
74
75void Enum::commit()
76{
77 assert(_setter);
78
79 if (!_selector)
80 return;
81
82 const int index = _selector->currentIndex();
83 if (index < 0)
84 return;
85
86 _setter((GVariant*)_selector->itemData(index).value<void*>());
87}
88
89void Enum::on_current_item_changed(int)
90{
91 commit();
92}
93
94} // prop
95} // pv