Ouputting an integer from a slider

projucer

#1

Hi there!

I’m just getting started with JUCE and I don’t have much prior experience with C++ at all, so I’d really appreciate any help you guys can offer.

I’m currently creating a pan dial and want to set the dials textbox suffix depending on the current value of the slider. For example, if the pan dial is set to +23 then I would want the textbox suffix of the slider to be “R”, to represent the right channel.

Is there a way to just output the sliders current value as an integer?

This is my code so far, but as you can see I’m stuck because I can’t work out how to output an integer from the slider.

//Show pan slider
addAndMakeVisible(panSlider);
panSlider.setSliderStyle(Slider::SliderStyle::Rotary);
panSlider.setValue(0);
panSlider.setRange(-64,64);
panSlider.onValueChange = [this] {

    //Check what pan integer currently is
    intPan = //Current value of the slider as an integer
    
    //Set it's suffix to L, R or C
    if (intPan > 0) {
        panSlider.setTextValueSuffix("R");
    } else if(intPan < 0) {
        panSlider.setTextValueSuffix("L");
    } else {
        panSlider.setTextValueSuffix("C");
    }
    else {} //else do nothing
};

I would thoroughly appreciate any advice/help!


#2

https://docs.juce.com/master/tutorial_slider_values.html


#3

Why do you need an integer value to do this?
Why not:

if (panSlider.getValue() >= 0.5) {
    ...
} else if (panSlider.getValue() < -0.5) {
    ...
} else {
    ...
}

I guess you could run into some floating-point weirdness in which case you could just round the value:

panInt = roundToInt<double>(panSlider.getValue());

https://docs.juce.com/develop/juce__MathsFunctions_8h.html


#4

Ah I see what you’re saying, yeah that’s great! Thanks for the help Jimmi.


#5

The cleanest solution is to modify the textFromValueFunction of the slider, that is exactly what it is there for:

slider.textFromValueFunction = [](double value)
{
    if (value < 0)
        return "L " + String (roundToInt (std::abs (value));
    else if (value > 0)
        return String (roundToInt (value)) + " R";

    return "0";
}

slider.valueFromTextFunction = [](String text)
{
    if (text.startsWith ("L "))
        return - text.substring (2).getDoubleValue();
    else if (text.endsWith (" R"))
        return text.dropLastCharacters (2).getDoubleValue();

    return text.getDoubleValue();
}

You can use the same lambdas for the parameter, and if you use the AudioProcessorValueTreeState::SliderAttachment, the lambdas from the parameter will be used in the slider automatically.

Not tested, HTH