【问题标题】:Swapping property values between objects在对象之间交换属性值
【发布时间】:2011-10-06 02:03:24
【问题描述】:

我在图中通过注释(。)创建了两个文本框。它们的大部分属性都已定义;回调函数启用窗口中的拖放动作。我为这些框创建了一个 uicontextmenu。右键单击可以从功能列表中选择后续操作。

我尝试添加的操作之一是在两个框之间交换字符串。我需要获取我当前右键单击的框的字符串,它应该与我随后左键单击的框中的字符串交换。我能否获得有关如何扩展 uimenu 功能以使其注册后续左键单击的建议?

【问题讨论】:

    标签: user-interface matlab figure


    【解决方案1】:

    您将需要手动存储最后点击的框。如果您使用 GUIDE 来设计您的 GUI,请使用 handles 结构,该结构被传递给回调函数。否则,如果您以编程方式生成组件,则嵌套回调函数可以访问在其封闭函数中定义的变量。

    编辑

    这是一个完整的示例:右键单击并从上下文菜单中选择“交换”,然后选择另一个文本框来交换字符串(左键单击)。请注意,我必须在两个步骤之间禁用/启用文本框才能触发 ButtonDownFcn(请参阅此 page 以获得解释)

    function myTestGUI
        %# create GUI
        hLastBox = [];          %# handle to textbox initiating swap
        isFirstTime = true;     %# show message box only once
        h(1) = uicontrol('style','edit', 'string','1', 'position',[100 200 60 20]);
        h(2) = uicontrol('style','edit', 'string','2', 'position',[400 200 60 20]);
        h(3) = uicontrol('style','edit', 'string','3', 'position',[250 300 60 20]);
        h(4) = uicontrol('style','edit', 'string','4', 'position',[250 100 60 20]);
    
        %# create context menu and attach to textboxes
        hCMenu = uicontextmenu;
        uimenu(hCMenu, 'Label','Swap String...', 'Callback', @swapBeginCallback);
        set(h, 'uicontextmenu',hCMenu)
    
        function swapBeginCallback(hObj,ev)
            %# save the handle of the textbox we right clicked on
            hLastBox = gco;
    
            %# we must disable textboxes to be able to fire the ButtonDownFcn
            set(h, 'ButtonDownFcn',@swapEndCallback)
            set(h, 'Enable','off')
    
            %# show instruction to user
            if isFirstTime
                isFirstTime = false;
                msgbox('Now select textbox you want to switch string with');
            end
        end
        function swapEndCallback(hObj,ev)
            %# re-enable textboxes, and reset ButtonDownFcn handler
            set(h, 'Enable','on')
            set(h, 'ButtonDownFcn',[])
    
            %# swap strings
            str = get(gcbo,'String');
            set(gcbo, 'String',get(hLastBox,'String'))
            set(hLastBox, 'String',str)
        end
    end
    

    【讨论】:

    • 是否必须将 leftClick 函数分配给框对象的 ButtonDownFcn 属性?使用 rightClick 函数作为交换字符串的机制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多