The Only Hacky Thing to Do: Reliably Reading Component Positions in a MATLAB uifigure

I wanted to read a grid child’s Position immediately after resizing its parent. Sometimes drawnow returned while the child still had its old size. A second read, with no further changes to the figure, gave a different rectangle.
A MATLAB uifigure has a browser-based client that computes grid layout and reports the resulting positions back to MATLAB. So when can MATLAB code read the updated values? In the layouts I tested, a wait inside that client gave me the same Position values as a later read. The wait starts with 220 ms without a container resize notification, then lets the client finish the layout work it has queued.
This post is an abridged English adaptation of my own article on Qiita (in Japanese). I used AI assistance to prepare the English write-up and reproduction files.
Caution: This trick relies on undocumented, private MATLAB internals. It was verified only by testing on Windows and may stop working in any release.
Why a position can change after drawnow
The uigridlayout documentation mentions that a child’s Position may lag when it is added to a grid. I saw the same kind of lag when resizing an existing grid. MATLAB updates the component properties as position change events arrive from the uifigure client. A read can occur while the client still has another relayout pending.
In the Windows releases I inspected (R2023a through R2026b), the Grid Layout controller used a 200 ms Lodash throttle for parent resize events, with both leading and trailing calls enabled. The first resize can run immediately. If another comes in during that interval, the trailing call can run on a timer, using the latest resize. If the grid contains another resizable container, that relayout can trigger another resize further down the tree.
The internal ViewModel method stabilize() waits for registered asynchronous work. The trailing timer hasn’t registered a relayout yet, so the ViewModel can report that its current work is done while the timer is still pending. A single requestAnimationFrame can also run before that timer fires.
How I waited for updated positions

Run JavaScript in the uifigure client

Reaching that window through the figure's hidden Controller follows the approach Yair Altman described in Customizing uifigures on Undocumented MATLAB. In the releases I tested, the window is on the controller's PlatformHost rather than its Container. The code registers a listener on the figure's ViewModel, then calls executeJS on that window. The JavaScript sends a completion event through the ViewModel after waiting for the layout. These steps use private APIs and require a figure whose host exposes a CEF window.
On Windows, use an ordinary uifigure from R2023a through R2024b. To use the same code in the desktop from R2025a through R2026b, create a separate figure window with the undocumented matlab.ui.internal.uifigureIsolated. Use fig = matlab.ui.internal.uifigureIsolated; in place of fig = uifigure; when creating the figure.

Wait for the grid’s resize work

  1. Wrap emitContainerResizeControllerEvent on the figure’s container controllers. Record the time of the most recent resize notification and keep that timestamp across waits. When installing a new hook, start the quiet period afresh because earlier notifications may have been missed.
  2. Wait for 220 ms without another notification. That is the Grid Layout controller’s 200 ms throttle interval plus a 20 ms margin. Each resize restarts the quiet period, so nested relayouts have time to schedule their own work. Give up after three seconds of continued activity.
  3. Await stabilize() when it exists, then wait one animation frame. In R2023a and R2023b, the grid relayout itself was scheduled as an animation-frame callback. In R2024a and later, the relayout was registered with the ViewModel.
  4. Send the completion event through the figure’s ViewModel so that it follows position notifications already dispatched on that channel. On receipt, read the MATLAB properties.
The 220 ms interval is derived from the throttle in the implementation I inspected. Both the throttle interval and the private APIs can change between releases.
Validation
I used a panel containing a two-row grid with a 'fit' label above a tab group. The second tab contained a nested grid and label. After the initial layout had settled, I measured a second wait and compared the outer label’s and tab group’s Position and the nested label’s getpixelposition(...,true). I took the first reading after the wait and a drawnow, and the second 0.5 seconds later.
In interactive MATLAB desktop sessions on Windows, I ran six trials per scenario in each release from R2023a through R2026b. All three rectangles agreed in all 192 trials.
The per-release median waits ranged from 241 to 249 ms after resizing the panel, enlarging the fit-row label, switching tabs, and enlarging the nested label. They ranged from 233 to 246 ms after only the panel resize and label enlargement, and from 296 to 375 ms after two panel resizes 50 ms apart. With no change, the wait took 8 to 12 ms.
The attached layoutWaitDemo.zip contains a smaller reproduction fixture, a single grid whose parent is resized twice within the throttle interval, and the same waitForFigureLayout.m and waitForFigureLayout.js shown below. To compare drawnow alone with the browser wait, extract the ZIP and run this command from the extracted folder.
matlab -batch "layoutWaitDemo(false, 8); layoutWaitDemo(true, 8)"
In this smaller fixture on Windows R2023a, R2024b, and R2026b, each release showed a position change after the first read in 8/8 baseline runs and 0/8 runs with the browser wait. The median extra waits were 362, 375, and 377 ms, respectively.
Using the wait in your own code
Save the two blocks below as waitForFigureLayout.m and waitForFigureLayout.js in the same folder and put that folder on the MATLAB path. Call the function once before editing the layout to install the resize hooks. After making your changes, call it again before reading Position. Keep the figure visible while waiting for the animation frame.
fig = uifigure;
panel = uipanel(fig, "AutoResizeChildren", "off", "Position", [20 20 300 250]);
grid = uigridlayout(panel, [1 1]);
child = uilabel(grid, "Text", "Grid child");
drawnow
waitForFigureLayout(fig); % Install hooks before the first layout change.
panel.Position(3:4) = [400 300];
drawnow
waitForFigureLayout(fig); % Wait for the queued resize work and its reply.
drawnow
position = child.Position

MATLAB file: waitForFigureLayout.m

function waitForFigureLayout(fig)
% waitForFigureLayout Dispatch the browser wait and receive its result on the figure ViewModel.
arguments (Input)
fig (1, 1) matlab.ui.Figure
end
% Find the browser window that hosts the figure.
% struct() reads every hidden property, so besides MATLAB:structOnObject it can
% emit unrelated deprecation warnings (JavaFrame, GraphicsSmoothing, ...).
% Silence all warnings only for these three calls.
warningState = warning("off", "all");
warningCleanup = onCleanup(@() warning(warningState));
figureData = struct(fig);
controller = struct(figureData.Controller);
host = struct(controller.PlatformHost);
clear warningCleanup
assert(isfield(host, "CEF") && ~isempty(host.CEF), ...
"This figure has no CEF window. Use uifigure through R2024b. " + ...
"In R2025a or later, create the figure with matlab.ui.internal.uifigureIsolated.");
viewModel = controller.ViewModel;
% Use a unique completion event for this request and subscribe before dispatch.
requestId = erase(string(java.util.UUID.randomUUID()), "-");
eventName = "FigureLayoutWaitCompleted_" + requestId;
reply = [];
listener = viewModel.addEventListener(char(eventName), @receive);
listenerCleanup = onCleanup(@() delete(listener));
configuration = struct("figureId", string(viewModel.getId()), ...
"channel", string(matlab.ui.internal.FigureServices.getUniqueChannelId(fig)), ...
"eventName", eventName);
source = fileread(fullfile(fileparts(mfilename("fullpath")), "waitForFigureLayout.js"));
script = replace(string(source), "__LAYOUT_WAIT_CONFIGURATION__", string(jsonencode(configuration)));
host.CEF.executeJS(char(script), 10);
% Yield to MATLAB callbacks and bound the wait for a missing browser reply.
clock = tic;
while isempty(reply) && toc(clock) < 8
pause(0.01);
end
assert(~isempty(reply), "Timed out waiting for the figure ViewModel reply.");
if isfield(reply, "error")
error("Browser layout wait failed: %s", string(reply.error));
end
clear listenerCleanup
function receive(~, event)
% receive Store the payload for this request's completion event.
reply = event.data;
end
end
JavaScript file: waitForFigureLayout.js
(config => {
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
require(["viewmodel/impl/ViewModelManagerFactory", "MW/componentframework/ControllerService"],
async (factory, service) => {
const managers = Object.values(factory._viewModelManagerCache)
.filter(manager => manager.hasById(config.figureId));
if (managers.length !== 1) {
throw new Error("Expected one ViewModel manager for this figure.");
}
const manager = managers[0];
const viewModel = manager.getById(config.figureId);
const send = result => viewModel.dispatchEvent(config.eventName, viewModel,
result);
try {
// Keep resize timestamps across calls in this demo figure.
const resize = viewModel.figureLayoutWaitResize ??= {
last: performance.now(), hooked: new WeakSet()
};
const cache = service.getInstance(config.channel)._controllerCache;
const controllers = cache instanceof Map ? [...cache.values()] : Object.values(cache);
let watched = 0;
for (const controller of controllers) {
const original = controller?.emitContainerResizeControllerEvent;
if (typeof original !== "function") continue;
watched++;
if (resize.hooked.has(controller)) continue;
controller.emitContainerResizeControllerEvent = function (...args) {
resize.last = performance.now();
return original.apply(this, args);
};
resize.hooked.add(controller);
resize.last = performance.now();
}
if (watched === 0) throw new Error("No resize emitters found.");
// Let pending browser work run, then wait out the trailing resize timer.
document.body.getBoundingClientRect();
await delay(0);
const started = performance.now();
while (performance.now() - resize.last < 220) {
if (performance.now() - started >= 3000) {
throw new Error("Resize activity did not settle within 3 seconds.");
}
await delay(10);
}
// Drain registered layout work where supported, then wait one frame.
const root = manager.getRoot();
if (typeof root.stabilize === "function") await root.stabilize();
await new Promise(resolve => requestAnimationFrame(resolve));
send({ completed: true });
} catch (error) {
send({ error: String(error) });
}
});
return config.eventName;
})(__LAYOUT_WAIT_CONFIGURATION__)
I'd rather not believe this far too hacky way is the only thing to do. Has anyone found a supported way to wait until a grid layout's updated positions are available on the MATLAB side? I'd also be interested in results from other platforms or nested layouts.
Yair Altman
Yair Altman alrededor de 18 horas hace
Thanks for the writeup.
Have you tried using the MarkedClean event ( https://undocumentedmatlab.com/articles/undocumented-hg2-graphics-events )? If it works, it could be much simpler, although just as undocumented as your approach.
Nobuto Kaitoh
Nobuto Kaitoh alrededor de 16 horas hace
Thanks for the suggestion!
I tried it on Windows in R2024b and R2026b. MarkedClean fired on a regular axes, but addlistener reported that the event wasn’t defined on the uifigure, either panel, or the grid layout in my repro.
Yair Altman
Yair Altman alrededor de 9 horas hace
For uifigures and uigridlayout, try using the ViewReady event
Nobuto Kaitoh
Nobuto Kaitoh alrededor de 1 hora hace
Thanks!
I’d tried ViewReady before settling on this approach.
I've rechecked in R2026b: on the uifigure, uigridlayout, and child panel, all three views stayed ready while the child panel’s Position was still stale. It seems to indicate that the view has initialized.