I want to connect a QSlider to a QDoubleSpinBox but while the code compiles fine and runs for simple QSpinBox, it doesn\'t work for QDoubleSpinBox
QSlider *h
As Dave Kilian answered, the signals and slots for QSlider don't use double. Also, Qt 4 does not automatically convert the types; it will not allow you to connect them. So, you will have to write your own conversion slot which updates the value of the other item.
QSlider and QDoubleSpinBox take different types of arguments in valueChanged
/setValue
(QSlider uses ints and QDoubleSpinBox uses doubles, of course). Changing the argument type for the slider's signal and slot might help:
connect(spinBox1, SIGNAL(valueChanged(double)),horizontalSlider1,SLOT(setValue(int)) );
connect(horizontalSlider1,SIGNAL(valueChanged(int)),spinBox1,SLOT(setValue(double)) );
I'm not sure if Qt can automatically handle this type conversion for you; if not, you'll have to define your own slots to call setValue() on the correct object
Hope this could help you.
#include <QApplication>
#include <QtGui>
#include <QVBoxLayout>
#include <QSlider>
#include <QLabel>
class DoubleSlider : public QSlider {
Q_OBJECT
public:
DoubleSlider(QWidget *parent = 0) : QSlider(parent) {
connect(this, SIGNAL(valueChanged(int)),
this, SLOT(notifyValueChanged(int)));
}
signals:
void doubleValueChanged(double value);
public slots:
void notifyValueChanged(int value) {
double doubleValue = value / 10.0;
emit doubleValueChanged(doubleValue);
}
};
class Test : public QWidget {
Q_OBJECT
public:
Test(QWidget *parent = 0) : QWidget(parent),
m_slider(new DoubleSlider()),
m_label(new QLabel())
{
m_slider->setOrientation(Qt::Horizontal);
m_slider->setRange(0, 100);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(m_slider);
layout->addWidget(m_label);
connect(m_slider, SIGNAL(doubleValueChanged(double)),
this, SLOT(updateLabelValue(double)));
updateLabelValue(m_slider->value());
}
public slots:
void updateLabelValue(double value) {
m_label->setText(QString::number(value, 'f', 2));
}
private:
QSlider *m_slider;
QLabel *m_label;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Test *wid = new Test();
wid->show();
return a.exec();
}
#include "main.moc"
You'll have to add your own slot which converts the argument type and emits a signal or updates the slider directly.
There is some example code on how to create your own slots and emit signals in this very similar question:
use a created vector as range for QDoubleSpinBox and QSlider