Clear Filters
Clear Filters

How to center Column names in table

74 views (last 30 days)
I use the uiStyle to make all my table entries to whichever type allignment I desire but the column names always seem to be left justified only. I thouight for e.g. when I specify "horizontalalignment" to "center" everything will be centered. Am I missing something?

Accepted Answer

Adam Danz
Adam Danz on 24 May 2021
Edited: Adam Danz on 25 May 2021
As far as I know,center-justification of uitable column names is not possible (as for r2021a).
A recent comment by MathWorks staff (Aug 2020) suggests a workaround that involves creating a second uitable placed above the main table, containing the header names and using uistyle to center the names. It wouldn't be too much work to put that together but it may require reworking existing code that assigns data to the UITable.
An alternative would be to convert your table to a cell array and move the header names to the first row the array. A cell array is needed if your data are not all strings, otherwise you could use a string array.
Then you can format the table to make it look like it contains a true header row.
The table on the left is the standard UITable with a header-row (aka "ColumnNames").
The table on the right shows the results of moving the header row into the data array and formatting the table to appear as unchanged.
Note that this changes how the table will be indexed since data starts are row #2.
% T: your initial data stored in a table
T = array2table(rand(5,3),'VariableNames',["Lancaster","Cincinnati","Sofia"]);
% 1. Convert table to cell, move header names into row 1.
C = [T.Properties.VariableNames; table2cell(T)];
% Create two uitables for comparison
uifig = uifigure();
uifig.Position(3:4) = [ 679 420];
uitTable = uitable(uifig,'data',T,'Units','Normalize','Position',[.05 .05 .4 .8]);
uitCell = uitable(uifig,'data',C,'ColumnName',{},'RowName',{},'Units','Normalize','Position',[.55 .05 .4 .8]);
% Switch order of shaded rows
uitCell.BackgroundColor = flipud(uitCell.BackgroundColor);
% Center all cells of the table & bolden the first row
uisCenter = uistyle('HorizontalAlignment', 'center');
uisBold = uistyle('FontWeight','bold');
addStyle(uitTable, uisCenter)
addStyle(uitCell, uisCenter)
addStyle(uitCell, uisBold, 'row',1)
Adam Danz
Adam Danz on 25 May 2021
Great, thanks for the feedback!
Martin Soltes
Martin Soltes on 20 Jan 2022
it works, the downside is your column names will be hidden if you use scroll bar..

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!