首页 > 解决方案 > 慢速数据游标回调期间的数据提示标签不正确

问题描述

添加自定义数据提示相当容易

f = figure();
plot( 1:100, sort(rand(100,1)) );
dc = datacursormode( f );
set( dc, 'UpdateFcn', @onDataCursorUpdate );

function txt = onDataCursorUpdate( tip, evt )
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) )};
end

但是更新功能可能需要一段时间才能获取数据提示信息。

就我而言,我想要包含的数据txt必须从数据库查询中获取。我意识到从性能的角度来看这是低效的,但它比将所有可能的数据提示属性存储在内存中要高效得多!

function txt = onDataCursorUpdate( tip, evt )
    info = mySlowQuery( tip.Position ); % fetch some data about this point
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           sprintf( 'Info: %s', info )};
end

此查询可能需要几分钟(!),不幸的是 MATLAB 在更新标签之前会更新数据提示的位置,因此您最终会得到以下事件序列:

问题

有没有办法防止这种情况发生,所以标签不正确时没有时间?

标签: matlabcallbackmatlab-figuredatatip

解决方案


您可以在回调开始时直接与数据提示交互以清除标签,然后运行回调的主体。输出txt仍会自动分配给 datatipString属性,但您可以在函数的早期手动更改它:

function txt = onDataCursorUpdate( tip, evt )
    % Clear the string first, use "loading..." as placeholder text
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           'Info: loading...'};
    tip.String = txt;
    % Now run the slow update
    info = mySlowQuery( tip.Position ); % fetch some data about this point
    txt = {sprintf( 'X: %g', tip.Position(1) ), ...
           sprintf( 'Y: %g', tip.Position(2) ), ...
           sprintf( 'Info: %s', info )};
end

推荐阅读