将命令附加到 UI 元素

 
 
 

创建包含所有必需元素的窗口之后,就会希望使用此窗口执行某些操作。每个控件均可执行由用户操作触发的 MEL 命令或程序。每个控件支持的操作类型均取决于该控件的性质。例如,按钮只有在被按住时才支持命令的执行,而滑块在被拖动时和更改值时均支持命令。有关每个控件支持的回调列表,请参见命令文档。

向按钮附加命令就是一个简单的示例。按住按钮时,以下命令将更改该按钮的标签文本。

脚本 5. 简单功能

window -width 200 -title "Test Window" ExampleWindow5;
 columnLayout;
 // Create the button.
 // 
 string $button = `button -label "Initial Label"`;
 // Add the command.
 // 
 string $buttonCmd;
 $buttonCmd = ("button -edit -label \"Final Label\" " + $button);
 button -edit -command $buttonCmd $button;
showWindow ExampleWindow5;

在本示例中,向按钮附加了单个命令。附加带有参数的程序同样简便。以下示例对上述示例进行了少许更改。

脚本 6. 程序中的简单功能

window -title "Test Window" -widthHeight 200 100 ExampleWindow6;
 columnLayout;
 // Create the button.
 // 
 string $button = `button -label "Initial Label"`;
 // Add the command.
 // 
 button -edit -command ("changeButtonLabel " + $button) $button;
showWindow ExampleWindow6;
proc changeButtonLabel (string $whichButton) {
 string $labelA;
 string $labelB;
 string $currentLabel;
 
 $currentLabel = `button -query -label $whichButton`;
 $labelA = "New Label A";
 $labelB = "New Label B";
 if ($currentLabel != $labelA) {
 button -edit -label $labelA $whichButton;
 } else {
 button -edit -label $labelB $whichButton;
 }
}

通常,控件发出的命令中会作为参数需要控件的值。若要避免在控件的状态更改时对其进行查询,可将其值作为字符串“#1”象征性地嵌入到命令中。控件更改值时,“#1”将在发出命令后替换为控件的实际值。包含多个值的组会将“#2”、“#3”等用作其不同组件的值。例如,包含三个场的浮动场组可在其命令中分别使用“#1”、“#2”和“#3”表示每个场的值。

通常,您会希望通过控件来显示节点的属性的值,并在该属性更改进行更新。达到此目的的最简单方法是使用“attr”版本的控件,即 attrFieldGrp,而不是 floatFieldGrp。如果“attr”命令不存在,则使用 connectControl 命令。