Question

I want to connect a QDoubleSpinBox with a QSlider like this:

QObject::connect(ui->myDoubleSpinBox, SIGNAL(valueChanged(double)), 
ui->mySlider, SLOT(setValue(double)));
    QObject::connect(ui->mySlider, SIGNAL(valueChanged(double)), 
ui->myDoubleSpinBox, SLOT(setValue(double)));

This won't work, for a QSlider only handles int values. So I think i need to add a custom slot to QSlider.
I thought about creating a new class derived from QSlider and then implementing the slot, like this:

QDoubleSlider.hpp

#ifndef QDOUBLESLIDER_H
#define QDOUBLESLIDER_H

#include <QSlider>

class QDoubleSlider : public QSlider
{
    Q_OBJECT
public:
    explicit QDoubleSlider(QObject *parent = 0);

signals:

public slots:
    void setValue(double givenValue);
};

#endif // QDOUBLESLIDER_H


QDoubleSlider.cpp

#include "qdoubleslider.h"

QDoubleSlider::QDoubleSlider(QObject *parent) :
    QSlider(parent)
{
}

void QDoubleSlider::setValue(double givenValue)
{
    // code
}

Now I have two problems:

  1. The compiler complains about an invalid conversion from QObject* to QWidget* in the constructor.
  2. I don't know how setValue works and thus I don't even know how to implement that slot.

Any ideas?

No correct solution

OTHER TIPS

  1. parent needs to be a QWidget*, just as the error states
  2. Slots work like regular member functions. You should probably store an exact double as a member and set the underlying slider to the appropriate integer equivalent. Remember to only send valueChanged signals if the value really changes.

Furthermore you should probably inherit from QWidget instead and have a QSlider as a child, as you do not want users of your class to change the integer range of your internal slider.

  1. just simply replace your QObject to QWidget, because QSlider constructor is QSlider ( QWidget * parent = 0 )
  2. you'd better have a new slot named setDoubleValue(double givenValue) and connect to this slot. in this slot, it is simple. like void QDoubleSlider::setDoubleValue(double givenValue) { setValue(static_cast<int>(givenValue)); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top