]> sigrok.org Git - pulseview.git/blame - pv/prop/enum.cpp
Enum: Use an iterator instead of iterating by indexes
[pulseview.git] / pv / prop / enum.cpp
CommitLineData
820c3dea
JH
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
24bb0bd1
JH
21#include <assert.h>
22
820c3dea
JH
23#include <QComboBox>
24
25#include "enum.h"
26
819f4c25
JH
27using std::pair;
28using std::vector;
820c3dea
JH
29
30namespace pv {
31namespace prop {
32
24bb0bd1 33Enum::Enum(QString name,
9b258927
JH
34 vector<pair<GVariant*, QString> > values,
35 Getter getter, Setter setter) :
36 Property(name, getter, setter),
820c3dea
JH
37 _values(values),
38 _selector(NULL)
39{
40}
41
9b258927
JH
42Enum::~Enum()
43{
1e5faac3
JH
44 for (vector< pair<GVariant*, QString> >::const_iterator i =
45 _values.begin(); i != _values.end(); i++)
46 g_variant_unref((*i).first);
9b258927
JH
47}
48
b1fe148e 49QWidget* Enum::get_widget(QWidget *parent, bool auto_commit)
820c3dea 50{
9ba4ca35 51 if (_selector)
820c3dea
JH
52 return _selector;
53
9b258927 54 GVariant *const value = _getter ? _getter() : NULL;
f352b9bb
JH
55 if (!value)
56 return NULL;
d191508b 57
820c3dea 58 _selector = new QComboBox(parent);
793f8096 59 for (unsigned int i = 0; i < _values.size(); i++) {
9b258927
JH
60 const pair<GVariant*, QString> &v = _values[i];
61 _selector->addItem(v.second, qVariantFromValue((void*)v.first));
7a2b7394 62 if (value && g_variant_equal(v.first, value))
d191508b
JH
63 _selector->setCurrentIndex(i);
64 }
820c3dea 65
9b258927
JH
66 g_variant_unref(value);
67
b1fe148e
JH
68 if (auto_commit)
69 connect(_selector, SIGNAL(currentIndexChanged(int)),
70 this, SLOT(on_current_item_changed(int)));
71
820c3dea
JH
72 return _selector;
73}
74
24bb0bd1
JH
75void Enum::commit()
76{
77 assert(_setter);
78
9ba4ca35 79 if (!_selector)
24bb0bd1
JH
80 return;
81
82 const int index = _selector->currentIndex();
83 if (index < 0)
84 return;
85
9b258927 86 _setter((GVariant*)_selector->itemData(index).value<void*>());
24bb0bd1
JH
87}
88
b1fe148e
JH
89void Enum::on_current_item_changed(int)
90{
91 commit();
92}
93
820c3dea
JH
94} // prop
95} // pv