Need help with slider and rectangle. Interaction between slider and rectangle

Hello! I don’t understand how can i change the size or how can i move a rectangle by moving a slider. So i created the slider and i made it a Listener. I added this function to my maincomponent.cpp.

void MainComponent::sliderValueChanged(Slider* slider)

After i draw a rectangle in

void MainComponent::paint (Graphics& g)

And i just want to change the size of this rectangle or the place or something else by mooving the slider. And i don’t understand how to do this. Please help.

Inheritance is certainly one way to go. Here’s a quick way using lambdas

/* MainComponent.H */
class MainComponent // notice I'm not deriving from Slider::Listener
    void paint(Graphics& g) override;
    Slider slider;
    Rectangle<int> rectangle;

then in the source file

/* MainComponent.cpp*/ 
:    slider (Slider::LinearVertical, Slider::TextBoxBelow) // initialize the slider 
    // set the slider range and step size
    slider.setRange (0.0, 1.0, 0.1);

    // set a callback using a lambda that captures the "this" pointer
    slider.onValueChange = [this] () {
        // scale the rectangle between the sizes (0, 0) and (200, 200)
        rectangle.setSize (slider.getValue() * 200, slider.getValue * 200);
    addAndMakeVisible (slider);
    // don't forget to set the component bounds or they won't be painted!
    slider.setBounds (0, 0, 50, 200);  // gonna be a big slider
    setSize (50 + 200, 200); // rectangle will fill up the right side of the component

void MyComponent::paint (Graphics& g) override {
    g.fillAll (Colours::white);
    g.setColour (Colours::red);
    g.fillRect (rectangle.translated (slider.getWidth(), 0);

I didn’t test any of this but it should give you a starting point

1 Like

…but keep inheriting from Component…
…and add a repaint() in the onValueChanged lambda, and it should be good to go…


@Holy_City, @daniel thank you, i will try