How to connect QSlider to QDoubleSpinBox

I want to connect QSlider to QDoubleSpinBox, but while the code compiles and works for a simple QSpinBox, it does not work for QDoubleSpinBox

QSlider *horizontalSlider1 = new QSlider();
QDoubleSpinBox *spinBox1 = new QDoubleSpinBox();

connect(spinBox1, SIGNAL(valueChanged(double)),horizontalSlider1,SLOT(setValue(double)) );
connect(horizontalSlider1,SIGNAL(valueChanged(double)),spinBox1,SLOT(setValue(double)) );
+5
source share
5 answers

QSlider and QDoubleSpinBox use different types of arguments in valueChanged/ setValue(QSlider uses ints, and QDoubleSpinBox uses, of course, doubles). Changing the argument type for the slider and slot signal can help:

connect(spinBox1, SIGNAL(valueChanged(double)),horizontalSlider1,SLOT(setValue(int)) );
connect(horizontalSlider1,SIGNAL(valueChanged(int)),spinBox1,SLOT(setValue(double)) );

I'm not sure Qt can automatically handle this type conversion for you; if not, you will need to define your own slots to call setValue () on the correct object

+6
source

, .

+7

, QSlider double. , Qt 4 ; . , , .

+3

, .

#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"
+1
0

All Articles