- Drag ListBox and Label into your app
- Click 'Code View' at the top right
- Click the + button in the Callbacks section of the Code Browser at left
- An Add Callback Function dialog will pop up, you can select your ListBox component which only has one available callback (ValueChangedFcn) and hit Add callback
- MATLAB will generate a function for you with value holding the selected item. Just add another line to set the Text property of the label: app.Label.Text = value;
How can I display a list box item as a string in a label in AppDesigner?
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Shanice Steinecke
le 29 Sep 2021
Commenté : Shanice Steinecke
le 30 Sep 2021
Dear Matlab Community,
I wanted to ask if it's possible to display a list box item, which is chosen by the user, as a string in a label. So for example if the user choses the list box item 'blue' then 'blue' should appear in the label. If the user choses 'red', 'red' should be displayed in the label. Is that possible? If yes, what does the code look like?
Thanks a lot!
Shanice
0 commentaires
Réponse acceptée
Dave B
le 29 Sep 2021
Yes this is possible. You can create a listbox, and a label, and assign a callback to the listbox that sets the label.
In general, to make components in apps do things when you interact with them, you assing a function to a property that ends in Fcn. These can point to functions you define in your m-code, or for simple things you can just define them inline as I did below.
Here's a demo of a programmatically generated app:
u = uifigure;
lst = uilistbox(u,'Items',["Red" "Green" "Blue" "Purple"]);
lbl = uilabel(u,'Text','Red');
lbl.Position([1 3])=[300 100];
lst.ValueChangedFcn = @(~,~)set(lbl,'Text',lst.Value);
If you use App Designer (click Apps at top, then 'Design App') the process looks like this:
5 commentaires
Dave B
le 30 Sep 2021
Sure...
It looks like you've added the callback function and just need to enter in the code.
Click in the ListBoxValueChanged item in the callbacks list, that will bring you to a spot of code you can edit:
Here's some code I put in that did the trick:
The value = app.ListBox.Value; is added by default from MATLAB, this just gives you a variable name to shorten things up.
The ind = strcmp(app.ListBox.ItemsData, value); line compares the character arrays in ItemsData to the one in value, giving a vector of logicals that can be used to index into Items (i.e. it says which ItemsData is selected, which corresponds to which Items is selected).
The app.Label.Text = app.ListBox.Items(ind); line uses the index to get the character array in Items, then it assigns that array to the label objects text property.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Develop uifigure-Based Apps dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!