A quick explain of the ListBox::setModel function

#1

i’m creating a listbox and trying to set the model and I need to use this function:

void ListBox::setModel (ListBoxModel* const newModel)
{
if (model != newModel)
{
    model = newModel;
    repaint();
    updateContent();
}
}

can anyone help me understand what is going on with those function arguements?

I know I need to set it up using:

MainComponent()
{
		

		addAndMakeVisible(listbox);
		listbox.setModel();

    setSize (400, 800);
}

I’m looking to pass in the ListBoxModel i’ve created into that setModel() function but I would like to understand how the pointer works in the function if possible.

0 Likes

#2

There’s not much to know. You just pass a pointer to your model into the setModel function. The ListBox does not own the model, so if you have allocated the model dynamically on the heap, you have to remember to delete the model yourself at some point when it’s no longer needed.

0 Likes

#3

Okay thanks for the response,

so what I’ve done is passed this in to the function

listboxB.setModel(&listbox);

now its appearing on my screen which is good. so when you say to delete the model myself, this is because it will forever reserve that space in memory or become a “dangling pointer”, so is the only time I need to worry about deleting this pointer/model/reference is if the application window is closed, or quit? and in the case of a audio plug-in, when the editor window is closed?

is there a better way to set the model, like when I create the named instance of the class, to avoid pointers and references altogether?

0 Likes

#4

It looks like the way you are doing it is already OK, the model would appear to be a non-heap allocated one. (So you don’t need to delete it etc.) The only thing to take care of would be to have the model declared before your listbox in your class members. (Because the class members that can be automatically destroyed are destroyed in reverse order of declaration.)

// ok
private:
  ListBoxModel model;
  ListBox listbox;

// not ok...The model would be destroyed before the ListBox, possibly
// leading to problems because the ListBox still has the pointer to the model
private:
  ListBox listbox;
  ListBoxModel model;
3 Likes

#5

Okay thanks!

0 Likes