PDA

View Full Version : QSpinBox : display values from a QVector



CTZStef
5th December 2013, 14:47
Hi,

I'd like to have a QSpinBox to display value from a QVector only. At first I thought that a new slot and signal in my widget would do the trick, using valueChanged(int) signal and setValue(int) slot from QSpinBox, but I enter an infinite loop since setValue emit valueChanged... :)
I heard that subclassing QAbstractSpinBox might work, but I really don't know how, nor which signals/slots to reimplement.
Any idea ? Maybe a better solution than subclassing ?

Thanks !!

zaphod.b
5th December 2013, 16:42
If it's only for the emit, have a look at QObject::blockSignals().

Santosh Reddy
5th December 2013, 17:10
Here is an example assuming the QVector is non-empty.


class SpinBox : public QSpinBox
{
Q_OBJECT
public:
explicit SpinBox(const QVector<int> & values, QWidget * parent = 0)
: QSpinBox(parent)
, mValues(values)
, mIndex(0)
{
qSort(mValues);
setMinimum(mValues.at(0));
setMaximum(mValues.at(mValues.size() - 1));
setValue(mValues.at(0));
}

protected:
void stepBy(int steps) // re-implementaion
{
mIndex += steps;
mIndex = qBound(0, mIndex, mValues.size() - 1);
setValue(mValues.at(mIndex));
}

private:
QVector<int> mValues;
int mIndex;
};

int main(int argc, char ** argv)
{
QApplication app(argc, argv);

QVector<int> values = QVector<int>() << 100 << 20 << 25 << 36 << 42 << 56 << 98 << 105;

SpinBox spinbox(values);
spinbox.show();

return app.exec();
}

Santosh Reddy
5th December 2013, 20:27
Did you explore using a QComboBox instead?

CTZStef
6th December 2013, 13:13
I use the same QSpinBox in two different contexts, one where it should work as usual, and another where I need to display only particular values. Thank you Santosh !