4

How can I set focus to a uifigure after the focus is switched out to a different figure?

For uicontrol, it is possible with set focus on one of its child elements. For example:

% create a new uicontrol text label
h = uicontrol('style','text','string','This is my figure');
% create a figure to switch the focus
figure;
% switch back
uicontrol(h)

However, for uifigure, adopting a similar code only creates a new uifigure.

Some code for you to try:

% create a new uifigure
h = uifigure('Name','This is my figure');
% create a new uilabel as a child of uifigure
lh = uilabel(h)
% create a figure to switch the focus
figure;
% this creates a new uifigure then switch back
uifigure(h)
% this creates an error as the first input argument must be a valid parent for uilabel
uilabel(lh)

Any idea, insight or contribution is appreciated.

Note your Matlab version should be at least 2016a, since this is when uifigure is introduced.

Anthony
  • 3,595
  • 2
  • 29
  • 38

1 Answers1

7

This is yet another one of the casualties of The MathWorks' bizarre strategy of releasing a new UI framework before it actually has any features. Granted, the new framework shows a lot of promise, but it still lags far behind the older graphics system in terms of functionality.

Rant aside, there's a quick workaround that tests fine in R2017a: toggle the visibility of the uifigure, which brings it to the fore. Here's a basic example:

function uifigurepop(uifigurehandle)
drawnow;
uifigurehandle.Visible = 'off';
uifigurehandle.Visible = 'on';
end

Which, if we bring this into the sample code:

% create a new uifigure
h = uifigure('Name','This is my figure');
% create a new uilabel as a child of uifigure
lh = uilabel(h)
% create a figure to switch the focus
figure;
% this creates a new uifigure then switch back
uifigure()
uifigurepop(h);

Your figure is now rendered topmost on the screen.

sco1
  • 12,154
  • 5
  • 26
  • 48
  • but there is no way to set the initial cursor focus on an element of the uifigure? e.g., uieditfield – Brian D Mar 27 '20 at 20:52
  • @BrianD this is possible too, take a look in [this Q&A](https://stackoverflow.com/q/62551221/3372061). – Dev-iL Jun 24 '20 at 09:10