Dynamic Creation in Qt of QSlider with associated QLCDNumber
I was wondering what's the best way to go about the following scenario?
I am dynamically creating QSliders that I wish to link to an associated QLCDNumber for display. The thing is I would like to have tenths available, so I would like to have a conversion between the QSLider and the QLCDNumber to divide by 10. At this point all I keep really is the QSlider, the QLCDNumbers I just create and forgot about. Is there an easy way of doing the conversion a开发者_如何学Pythonnd connection without having to keep too much information?
Thanks in advance.
I'd try something along the following lines:
// create a new signal in your parent widget
signals:
void updateLCDNumber(double);
// and a slot which performs the conversion
private slots:
void performConversion(int value)
{
double convertedValue = value * 0.1;
emit(updateLCDNumber(convertedValue));
}
// then set the signals/slots up like this
connect(mySlider, SIGNAL(valueChanged(int)), this, SLOT(performConversion(int)));
connect(this, SIGNAL(updateLCDNumber(double)), myLCDNumber, SLOT(display(double)));
Afterwards you can completely "forget" about your LCD number, i.e. you don't need to keep a pointer or reference.
EDIT: A solution for several sliders:
class MySlider : public QSlider
{
Q_OBJECT
public:
MySlider(QWidget *parent=0) : QSlider(parent)
{
connect(this, SIGNAL(valueChanged(int)), this, SLOT(performConversion(int)));
}
signals:
void updateLCDNumber(double);
private slots:
void performConversion(int value)
{
double convertedValue = value * 0.1;
emit(updateLCDNumber(convertedValue));
}
};
Now create MySlider
instances instead of QSlider
ones and connect your QLCDNumbers
:
connect(mySlider1, SIGNAL(updateLCDNumber(double)), myLCDNumber1, SLOT(display(double)));
connect(mySlider2, SIGNAL(updateLCDNumber(double)), myLCDNumber2, SLOT(display(double)));
...
This way you can also implement different conversion factors and the like, just modify the MySlider
implementation.
I hope that helps.
This is basically what I ended up using; it seems to work (though it violates the whole object oriented philosophy).
signalMapper= new QSignalMapper(this);
QObject::connect(tmpSlider, SIGNAL(valueChanged(int)), signalMapper, SLOT(map()));
sliderMapper->setMapping(tmpSLider, tmpLCDNumber);
QObject::connect(signalMapper, SIGNAL(mapped(QWidget*)), this, SLOT(updateLCD(QWidget*)))
...
void MyClass::updateLCD(QWidget* lcdNum){
((QLCDNumber*)lcdNum)->display(((QSlider*)(signalMapper->mapping(lcdNum)))->value()*.1);
}
精彩评论