Draggable Label

gui

#1

Hey,
I’m trying to create a label component which is draggable.

At first I tried to use composition:
I created a component which has a label and a ComponentDragger. I used addMouseListener(this, true) in my component to get mouseDown and mouseDrag event which happend in the label. But when the label is being edited, the dragger of the parent component avoid text selection (as the component is dragged instead). So I had to use conditional in my component callback: if (mLabel.isBeingEdited() == false).

I also I tried to use inheritance:

class CustomLabel : public Label
{    
public:  
     CustomLabel()
     {
        setFont(Font (16.0f, Font::bold));
        setText("Test", dontSendNotification);
        setColour(Label::textColourId, Colours::lightgreen);
        setJustificationType(Justification::centred); 
        setEditable(false, true);
     }

    void mouseDown(const MouseEvent& event) override
    { 
        mDragger.startDraggingComponent(this, event);
    }

     void mouseDrag(const MouseEvent& event) override
    {
        mDragger.dragComponent(this, event, nullptr);
    }

private:
    ComponentDragger mDragger;
};

This seems to work but I have no Idea why, I expected that I would still need the condition in mousedown and mousedrag listener. But I don’t … Any idea why ?

What is the nicest way to do this ? I’m new to Juce so I’m trying to learn the right way to do things. Thanks for your help and sorry if it sounds like a fake problem.
Best,


#2

what about making a draggable component that holds a label and has some of the mouseListener methods overridden to detect mouse events happening within the label child?


#3

Hey,
It’s what I tried first (see first part of my post). The inheritance solution doesn’t have to check if the label is being edited. But I don’t know why, do you have any idea ?
Thanks for the help


#4

I suggested Composition, not inheritance.
e.g.

class MyDraggableLabel : public Component
{
public: 
   MyDraggableLabel() 
   {
       addMouseListener(this, true);
   }
   void mouseDown(const MouseEvent& event) override
   { 
        dragger.startDraggingComponent(this, event);
   }
   void mouseDrag(const MouseEvent& event) override
   {
        dragger.dragComponent(this, event, nullptr);
   }
   void resized() override
   {
      label.setBounds( getLocalBounds() );
   }
private:
   Label label;
   ComponentDragger dragger;
};

untested, but you get the idea…


#5

Hey matkatmusic,
Thanks for the answer.
With your code if you clicked on the label to set some text and then try to use the cursor to select a part of the text you wrote, the label will be dragged instead. So you have to check the label is not in edit mode before dragging: mLabel.isBeingEdited()
But with inheritance I don’t get this problem, no idea why … Could you tell me more about your choice for inheritance ?
Thanks again for the help.
Best,