文档库 最新最全的文档下载
当前位置:文档库 › matlab中的GUI介绍及用法

matlab中的GUI介绍及用法

matlab中的GUI介绍及用法
matlab中的GUI介绍及用法

Creating Graphical User Interfaces

Programming Callbacks for GUI Components(部件,组建,复数)

This section explains how to program the callbacks for some specific GUI components. Callback Properties 性能,道具,内容describes the different kinds of callbacks.

See a component's property reference page to determine which callbacks apply for that component. Setting Component Properties -- The Property Inspector 检察院,巡视员provides links to the property reference pages.

This section provides information on the following topics: Toggle Button Callback Radio Buttons Check Boxes Edit Text Sliders List Boxes Pop-Up Menus Panels Button Groups Axes ActiveX Controls Figures

Input and Output Arguments Toggle Button Callback

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Toggle索结绳纽Button Callback

The callback for a toggle button needs to query疑问,询问,质问the toggle button to determine what state it is in. MA TLAB sets the Value property equal to the Max property when the toggle button is depressed (Max is 1 by default) and equal to the Min property when the toggle button is not depressed (Min is 0 by default).

From the GUI M-file

The following code illustrates how to program the callback in the GUI M-file.

function togglebutton1_Callback(hObject, eventdata, handles)

button_state = get(hObject,'Value');

if button_state == get(hObject,'Max')

% toggle button is pressed

elseif button_state == get(hObject,'Min')

% toggle button is not pressed

end

Note If you have toggle buttons that are managed by a button group component, you must include the code to control them in the button group's SelectionChangeFcn callback function, not in the individual toggle button Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages. See Button Groups for more information.

Adding an Image to a Push Button or Toggle Button

Assign the CData property an m-by-n-by-3 array of RGB values that define a truecolor image. For example, the array a defines 16-by-128 truecolor image using random values between 0 and 1 (generated by rand).

a(:,:,1) = rand(16,128);

a(:,:,2) = rand(16,128);

a(:,:,3) = rand(16,128);

set(hObject,'CData',a)

See ind2rgb for information on converting an (X, MAP) image to an RGB image. Programming Callbacks for GUI Components Radio Buttons

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Radio Buttons

You can determine the current state of a radio button from within its callback by querying the state of its Value property, as illustrated in the following example:

if (get(hObject,'Value') == get(hObject,'Max'))

% then radio button is selected-take approriate action

else

% radio button is not selected-take approriate action

end

Note If you have radio buttons that are managed by a button group component, you must include the code to control them in the button group's SelectionChangeFcn callback function, not in the individual radio button Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages. See Button Groups for more information.

Toggle Button Callback Check Boxes

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Check Boxes

You can determine the current state of a check box from within its callback by querying the state of its Value property, as illustrated in the following example:

function checkbox1_Callback(hObject, eventdata, handles)

if (get(hObject,'Value') == get(hObject,'Max'))

% then checkbox is checked-take approriate action

else

% checkbox is not checked-take approriate action

end

Radio Buttons Edit Text

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Creating Graphical User Interfaces

Edit Text

To obtain the string a user typed in an edit box, get the String property in the callback.

function edittext1_Callback(hObject, eventdata, handles)

user_string = get(hObject,'string');

% proceed with callback...

For example, setting Max to 2, with the default value of 0 for Min, enables users to select multiple lines

Obtaining Numeric Data from an Edit Text Component

MATLAB returns the value of the edit text String property as a character string. If you want users to enter numeric values, you must convert the characters to numbers. You can do this using the str2double command, which converts strings to doubles. If the user enters nonnumeric characters, str2double returns NaN.

You can use the following code in the edit text callback. It gets the value of the String property and converts it to a double. It then checks whether the converted value is NaN (isnan), indicating the user entered a nonnumeric character and displays an error dialog (errordlg).

function edittext1_Callback(hObject, eventdata, handles)

user_entry = str2double(get(hObject,'string'));

if isnan(user_entry)

errordlg('You must enter a numeric value','Bad Input','modal')

end

% proceed with callback...

Triggering Callback Execution

For both UNIX and Windows, clicking on the menu bar of the figure window causes the edit text callback to execute. Clicking on other components or the background of the GUI also executes the callback.

Check Boxes Sliders

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Sliders

You can determine the current value of a slider from within its callback by querying its Value property, as illustrated in the following example:

function slider1_Callback(hObject, eventdata, handles)

slider_value = get(hObject,'Value');

% proceed with callback...

The Max and Min properties specify the slider's range (Max - Min).

Edit Text List Boxes

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

List Boxes

Triggering Callback Execution

MATLAB evaluates the list box's callback after the mouse button is released or after certain key press events. The arrow keys change the V alue property and trigger callback execution. Enter and Space do not change the Value property but trigger callback execution.

If the user double-clicks, the callback executes after each click. MATLAB sets Selection Type to normal on the first click and to open on the second click. The callback can query the Selection Type property to determine if it was a single- or double-click.

List Box Examples

See the following examples for more information on using list boxes: List Box Directory Reader -- Shows how to creates a GUI that displays the contents of directories in a list box and enables

users to open a variety of file types by double-clicking on the filename. Accessing Workspace Variables from a List Box -- Shows how to access variables in the MA TLAB base workspace from a list box GUI.

Sliders Pop-Up Menus

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Pop-Up Menus

You can program the pop-up menu callback to work by checking only the index of the item selected (contained in the V alue property) or you can obtain the actual string contained in the selected item.

This callback checks the index of the selected item and uses a switch statement to take action based on the value. If the contents of the pop-up menu is fixed, then you can use this approach. function popupmenu1_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');

switch val

case 1

% The user selected the first item

case 2

% The user selected the second item

% proceed with callback...

This callback obtains the actual string selected in the pop-up menu. It uses the value to index into the list of strings. This approach may be useful if your program dynamically loads the contents of the pop-up menu based on user action and you need to obtain the selected string. Note that it is necessary to convert the value returned by the String property from a cell array to a string. function popupmenu1_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');

string_list = get(hObject,'String');

selected_string = string_list{val}; % convert from cell array

% to string

% proceed with callback...

List Boxes Panels

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Panels

Panels group GUI components and can make a user interface easier to understand by visually grouping related controls. Panel children can be panels and button groups as well as axes and user interface controls. The position of each component within a panel is interpreted relative to the panel. If the panel is resized, you may want to reposition its components.

The following callback executes and gets the Position property of uipanel2 whenever the panel is resized. Once you have the size data contained in the Position property, you can modify the Position properties of the child components to reposition them. Use the Children property of uipanel2 to get the handles of its child components.

function uipanel2_ResizeFcn(hObject, eventdata, handles)

% hObject handle to uipanel1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDA TA)

pos = get(hObject,'Position');

% proceed with callback...

Pop-Up Menus Button Groups

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Button Groups

Button groups are like panels, but can be used to manage exclusive selection behavior for radio buttons and toggle buttons. The button group's SelectionChangeFcn callback is called whenever a

selection is made.

For radio buttons and toggle buttons that are managed by a button group, you must include the code to control them in the button group's SelectionChangeFcn callback function, not in the individual uicontrol Callback functions. A button group overwrites the Callback properties of radio buttons and toggle buttons that it manages.

This example of a SelectionChangeFcn callback uses the Tag property of the selected object to choose the appropriate code to execute.

function uibuttongroup1_SelectionChangeFcn(hObject,eventdata,handles)

% hObject handle to uipanel1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDA TA)

switch get(hObject,'Tag') % Get Tag of selected object

case 'radiobutton1'

% code piece when radiobutton1 is selected goes here

case 'radiobutton2'

% code piece when radiobutton2 is selected goes here

% ...

end

Note For a uibuttongroup, contrary to the automatically generated comment, hObject is the handle of the selected radio button or toggle button, and not the handle of the uibuttongroup. Use handles.uipaneln as the handle of the uibuttongroup.

The code above refers to the handle of uipanel1 rather than the handle of uibuttongroup1, because a uibuttongroup is a kind of uipanel.

Panels Axes

? 1994-2005 T he MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

Axes

Axes enable your GUI to display graphics (e.g., graphs and images). Like all graphics objects, axes have properties that you can set to control many aspects of its behavior and appearance. See

Axes Properties" in the MATLAB Graphics documentation for general information on axes objects.

Axes Callbacks

Axes are not uicontrol objects, but can be programmed to execute a callback when users click a mouse button in the axes. Use the axes ButtonDownFcn property to define the callback.

Plotting to Axes in GUIs

If your GUI contains axes, you should make sure that the Command-line accessibility option in the GUI Options dialog is set to Callback (the default). This enables you to issue plotting commands from callbacks without explicitly specifying the target axes. See Command-Line Accessibility for more information about how this option works.

Note If your GUI is opened as the result of another GUI's callback, you might need to explicitly specify the target axes. See GUIs with Multiple Axes.

Example: Displaying an Image on an Axes

This example shows how to display an image on an axes. The example Displays an image file on an axes. Resizes the axes to fit the image. Resizes the GUI so that its width and height are 100 pixels larger than the image file.

To build the example: Open a blank template in the Layout Editor. Drag an axes into the layout area. Select M-file editor from the View menu. Add the following code to the opening function: set(hObject, 'Units', 'pixels');

handles.banner = imread([matlabroot filesep 'demos' filesep

'banner.jpg']); % Read the image file banner.jpg

info = imfinfo([matlabroot filesep 'demos' filesep

'banner.jpg']); % Determine the size of the image file

position = get(hObject, 'Position');

set(hObject, 'Position', [position(1:2) info.Width + 100

info.Height + 100]);

axes(handles.axes1);

image(handles.banner)

set(handles.axes1, ...

'Visible', 'off', ...

'Units', 'pixels', ...

'Position', [50 50 info.Width info.Height]);

When you run the GUI, it appears as in the following figure.

The preceding code performs the following operations: Reads the image file banner.jpg using the command imread. Determines the size of the image file in pixels using the command imfinfo. Sets the width and height of the GUI to be 100 pixels greater than the corresponding dimensions of the image file, which are stored as info.Width and info.Height, respectively. The width and height of the GUI are the third and fourth entries of the vector position. Displays the image in the axes using the command image(handles.banner). Makes the following changes to the axes properties: Sets 'Visible' to 'off' so that the axes are invisible Sets 'Units' to 'pixels' to match the units of the vector position Sets 'Position' to [50, 50, info.Width info.Height] to set the size of the axes equal to that of the image file, and center the image file on the GUI.

GUIs with Multiple Axes

If a GUI has multiple axes, you should explicitly specify which axes you want to target when you issue plotting commands. You can do this using the axes command and the handles structure. For example,

axes(handles.axes1)

makes the axes whose Tag property is axes1 the current axes, and therefore the target for plotting commands. You can switch the current axes whenever you want to target a different axes. See GUI with Multiple Axes for an example that uses two axes.

Button Groups ActiveX Controls

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

Creating Graphical User Interfaces

ActiveX Controls

You can insert an ActiveX control into your GUI if you are running MATLAB on Microsoft Windows. When you drag an ActiveX component from the component palette into the layout area,

GUIDE displays a dialog in which you can select any registered ActiveX control on your system. When you select an ActiveX control and click Create, the control appears as a small box in the Layout Editor. You can then program the control to do what you want it to.

See MA TLAB COM Client Support in the online MATLAB documentation to learn more about ActiveX controls.

This section covers the following topics: Adding an ActiveX Control to a GUI Viewing the ActiveX Properties with the Property Inspector Adding a Callback to an ActiveX Control to Change a Property Adding a Uicontrol to Change an ActiveX Control Property Viewing the Methods for an ActiveX Control Saving a GUI that Contains an ActiveX Control Compiling a GUI that Contains an ActiveX Control

Adding an ActiveX Control to a GUI

This section shows how to add an ActiveX control to a GUI. The section describes a simple ActiveX control that displays a circle. After adding the ActiveX control, you can program the GUI to change the radius of the circle and display the new value of the radius.

Note If MATLAB is not installed locally on your computer -- for example, if you are running MATLAB over a network -- you might not find the ActiveX control described in this example. To register the control, see Registering Controls and Servers in the online MA TLAB documentation.

To make the example, Open a new GUI in GUIDE and drag an ActiveX control from the component palette into the Layout Editor. Scroll down the ActiveX Control List and select Mwsamp Control. This displays a preview of the ActiveX control Mwsamp, as shown in the following figure.

Click Create to display the ActiveX control in the Layout Editor, and resize the control to approximately the size of the square shown in the preview pane. You can do this by clicking and dragging a corner of the control, as shown in the following figure.

Click the Run button on the toolbar and save the GUI when prompted. GUIDE displays the GUI shown in the following figure.

Viewing the ActiveX Properties with the Property Inspector

To view the properties of the ActiveX control, right-click the control in the Layout Editor and

select Property Inspector, or select Property Inspector from the View menu. This displays the Property Inspector, as shown in the following figure.

The ActiveX control mwsamp has just two properties: Label, which contains the text that appears at the top of the control Radius, the default radius of the circle, which is 20

The example in the next section shows how to program the GUI to Change the radius when a user clicks the circle Change the label to display the new radius

Adding a Callback to an ActiveX Control to Change a Property

To change a property of the control when a user performs an action, you need to add a callback to an ActiveX control. For example, to make mwsamp decrease the radius of the circle by 10 percent and display the new value each time a user clicks the ActiveX control, you can add an event, or callback, corresponding to the click action. To do so, Right-click the ActiveX control in the Layout Editor to bring up its context menu. In the context menu, place the cursor over View Callbacks and select Click. This creates a callback called activex1_Click and opens the GUI M-file with the first line of the callback highlighted. Add the following commands to the activex1_Click callback:

hObject.radius = .9*hObject.radius;

https://www.wendangku.net/doc/909146022.html,bel = ['Radius = ' num2str(hObject.radius)];

refresh(handles.figure1);

Add the following command to the opening function:

https://www.wendangku.net/doc/909146022.html,bel = ...

['Radius = ' num2str(handles.activex1.radius)];

Run the GUI.

Now, each time you click the ActiveX control, the radius of the circle is reduced by 10 percent and the new value of the radius is displayed. The following figure shows the GUI after clicking the circle six times.

G

If you click the GUI enough times, the circle disappears entirely.

Adding a Uicontrol to Change an ActiveX Control Property

You can also add other Uicontrols to the GUI to change the properties of an ActiveX control. For example, you can add a slider that changes the radius of the circle in the Mwsamp GUI. To do so, Drag a slider into the layout area. Right-click the slider and select M-file Editor. Add the following command to the slider1 callback:

handles.activex1.radius = ...

get(hObject, 'Value')*handles.default_radius;

https://www.wendangku.net/doc/909146022.html,bel = ...

['Radius = ' num2str(handles.activex1.radius)];

refresh(handles.figure1);

Add the following command to the opening function:

handles.default_radius = handles.activex1.radius;

Add the following command at the end of the code in the activex1_Click callback:

set(handles.slider1, 'Value', ...

hObject.radius/handles.default_radius);

Run the GUI.

When you move the slider by clicking and dragging, the radius changes to a new value between 0 and the default radius of 20, as shown in the following figure.

The command

handles.activex1.radius = ...

get(hObject, 'Value')*handles.default_radius;

does the following: Gets the Value of the slider, which in this example is a number between 0 and 1, the default values of the slider's Min and Max properties. Sets handles.activex1.radius equal to the Value times the default radius.

Note that clicking the ActiveX control causes the slider to change position corresponding to the new value of the radius. The command

set(handles.slider1, 'Value', ...

hObject.radius/handles.default_radius);

in the activex1_Click callback resets the slider's Value each time the user clicks the ActiveX control.

Viewing the Methods for an ActiveX Control

To view the available methods for the ActiveX control, you first need to obtain the handle to the control. One way to do this is the following: In the GUI M-file, add the command keyboard on a separate line of the activex1_Click callback. The command keyboard puts MA TLAB in debug mode and pauses at the activex1_Click callback when you click the ActiveX control. Run the GUI and click the ActiveX control.

The handle to the control is now set to hObject. To view the methods for the control, enter methodsview(hObject)

at the MATLAB prompt. This displays the available methods in a new window, as shown in the following figure.

Alternatively, you can enter

methods(hObject)

which displays the available methods in the Command Window.

For more information about methods for ActiveX controls, see Invoking Methods in the online MATLAB documentation. See the reference pages for methodsview and methods for more information about these functions.

Saving a GUI that Contains an ActiveX Control

When you save a GUI that contains ActiveX controls, GUIDE creates a file in the current directory for each such control. The filename consists of the name of the GUI followed by an underscore (_) and activexn, where n is a sequence number. For example, if the GUI is named mygui then the filename would be mygui_activex1. The filename does not have an extension.

Compiling a GUI that Contains an ActiveX Control

If you use the MATLAB Compiler mcc command to compile a GUI that contains an ActiveX control, you must use the -a flag to add the ActiveX file, which GUIDE saves in the current

directory, to the CTF archive. Your command should be similar to this

mcc -m mygui -a mygui_activex1

where mygui_activex1 is the name of the ActiveX file. See the MA TLAB Compiler documentation for more information. If you have more than one such file, use a separate -a flag for each file. You must have installed the MATLAB Compiler to compile a GUI.

Axes Figures

? 1994-2005 The MathWorks, Inc. ? Terms of Use ? Patents ? Trademarks

相关文档