MATLAB AppDesigner ListBox - PullRequest
       1

MATLAB AppDesigner ListBox

1 голос
/ 21 октября 2019

Добрый день!

В настоящее время я пытаюсь создать приложение с MATLAB с помощью App Designer. Цель состоит в том, чтобы иметь возможность наносить данные с использованием нескольких файлов GPX, что я успешно сделал. Мне любопытно, как я должен заполнить свой список.

Есть ли способ для Listbox заполниться именами файлов в зависимости от выбранной папки?

1 Ответ

0 голосов
/ 21 октября 2019

Вы можете использовать dir для вывода списка содержимого папки, преобразования списка имен в массив ячеек и заполнения элементов ListBox массивом ячеек.

Предположим, у вас есть кнопка с обратным вызовом ButtonButtonPushed, и вы хотите позволить пользователю выбрать папку, а затем заполнить список всеми файлами * .gpx.

Вы можете сделать это следующим образом:

% Button button pushed function
function ButtonButtonPushed(app)
    selpath = uigetdir(); %Open dialog box for selecting folder.
    gpx_files = dir(fullfile(selpath, '*.gpx')); %Dir all *.gpx in selected folder.
    %Populate listbox with file names:
    app.ListBox.Items = {gpx_files(:).name};
end

Оператор app.ListBox.Items = {gpx_files(:).name}; заполняет ListBox.

  • gpx_files(:).name - список имен файлов.
  • {gpx_files(:).name} создает массив ячеек из списка.
  • app.ListBox.Items = {gpx_files(:).name}; Устанавливает свойство Items ListBox с созданным массивом ячеек.

Получение полного пути к выбранному файлу:

  1. Сохранение выбранной папки:
    Добавление личногосвойство с именем selpath (используйте красный P + в конструкторе [представление кода], чтобы добавить новое свойство и отредактируйте имя свойства):

    properties (Access = private)
        selpath % Store selected path
    end
    
  2. Сохранить выбранный путьв свойстве selpath при нажатии кнопки:

    % Button pushed function: Button
    function ButtonButtonPushed(app, event)
        app.selpath = uigetdir(); %Open dialog box for selecting folder.
        gpx_files = dir(fullfile(app.selpath, '*.gpx')); %Dir all *.gpx in selected folder.
    
        %Populate listbox with file names:
        app.ListBox.Items = {gpx_files(:).name};
    end
    

    Теперь выбранный путь сохраняется в app.selpath.

  3. Добавить функцию обратного вызова «ListBoxChangeValue» (щелкните правой кнопкой мыши поле списка в режиме конструктора).

  4. Редактировать код функции ListBoxValueChanged:
    value Возвращенное value = app.ListBox.Value; - это имя выбранного файла (вам не нужно использовать strcmpi).
    Используйте функцию fullfile, чтобы объединить путь с именем файла.

    % Value changed function: ListBox
    function ListBoxValueChanged(app, event)
        value = app.ListBox.Value;
        selected_file = fullfile(app.selpath, value); %Get the full path of selected file.
        disp(selected_file) %Change the code to load selected_file
    end
    

    Приведенный выше код отображает строку selected_file в командном окне.
    Замените disp(selected_file) собственным кодом (загрузка и создание файла gpx).


Вот полный код App1 (большая часть кода была сгенерирована автоматически):

classdef App1 < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure      matlab.ui.Figure
        Button        matlab.ui.control.Button
        LabelListBox  matlab.ui.control.Label
        ListBox       matlab.ui.control.ListBox
    end


    properties (Access = private)
        selpath % Store selected path
    end


    % Callbacks that handle component events
    methods (Access = private)

        % Code that executes after component creation
        function startupFcn(app)

        end

        % Button pushed function: Button
        function ButtonButtonPushed(app, event)
            app.selpath = uigetdir(); %Open dialog box for selecting folder.
            gpx_files = dir(fullfile(app.selpath, '*.gpx')); %Dir all *.gpx in selected folder.

            %Populate listbox with file names:
            app.ListBox.Items = {gpx_files(:).name};
        end

        % Value changed function: ListBox
        function ListBoxValueChanged(app, event)
            value = app.ListBox.Value;
            selected_file = fullfile(app.selpath, value); %Get the full path of selected file.
            disp(selected_file) %Change the code to load selected_file
        end
    end

    % Component initialization
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure and hide until all components are created
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.Position = [101 101 640 480];
            app.UIFigure.Name = 'UI Figure';

            % Create Button
            app.Button = uibutton(app.UIFigure, 'push');
            app.Button.ButtonPushedFcn = createCallbackFcn(app, @ButtonButtonPushed, true);
            app.Button.Position = [43 380 114 49];
            app.Button.Text = 'Select Folder';

            % Create LabelListBox
            app.LabelListBox = uilabel(app.UIFigure);
            app.LabelListBox.HorizontalAlignment = 'right';
            app.LabelListBox.VerticalAlignment = 'top';
            app.LabelListBox.Position = [300 412 44 15];
            app.LabelListBox.Text = 'List Box';

            % Create ListBox
            app.ListBox = uilistbox(app.UIFigure);
            app.ListBox.ValueChangedFcn = createCallbackFcn(app, @ListBoxValueChanged, true);
            app.ListBox.Position = [359 355 100 74];

            % Show the figure after all components are created
            app.UIFigure.Visible = 'on';
        end
    end

    % App creation and deletion
    methods (Access = public)

        % Construct app
        function app = App1

            % Create UIFigure and components
            createComponents(app)

            % Register the app with App Designer
            registerApp(app, app.UIFigure)

            % Execute the startup function
            runStartupFcn(app, @startupFcn)

            if nargout == 0
                clear app
            end
        end

        % Code that executes before app deletion
        function delete(app)

            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...