使用html内容在matlab中更改表格单元格的背景颜色

Sep*_*our 0 matlab user-interface cell background-color matlab-uitable

我们知道uitable支持html内容
的类似于我想要的示例在这里
解决我在matlab中的按钮回调中使用此代码之前所问的问题:

color = uisetcolor;  
numberOfClasses = str2num(get(handles.edtNumClass,'String'));  
if handles.index == 0  
    handles.tableData = cell(numberOfClasses,2);
    guidata(hObject,handles);
end
handles.index = handles.index+1;
handles.tableData(handles.index,1)=cellstr(get(handles.edtNameClass,'String'));
handles.tableData(handles.index,2)=cellstr('<html><span style="background-color:  rgb(color(1,1),color(1,2),color(1,3));"></span></html>');
set(handles.uitable2,'data',handles.tableData);
Run Code Online (Sandbox Code Playgroud)

我的问题是这行不起作用:

handles.tableData(handles.index,2)=cellstr('<html><span style="background-color:  rgb(color(1,1),color(1,2),color(1,3));"></span></html>');
Run Code Online (Sandbox Code Playgroud)

我的意思是当我在matlab中打开工作区时,我看到handle.tableData(handles.indexes,2)被设置为字符串.
但即使这个html代码没有显示为简单的字符串,背景颜色也不会改变.细胞没有变化!
和matlab没有错误信息!
请注意,我甚至使用了此代码,但没有任何变化.

handles.tableData(handles.index,2)=cellstr('<html><span style="background-color:  #FF0000;"></span></html>');
Run Code Online (Sandbox Code Playgroud)

Amr*_*mro 5

@Floris是正确的,字符串不是"评估"为MATLAB代码,需要显式写入颜色.这是一个小例子:

%# data
X = {
    'Alice'   1
    'Bob'     2
    'Charlie' 3
    'Dave'    4
};

%# get color from user
c = uisetcolor();

%# format color as: rgb(255,255,255)
%#clr = sprintf('rgb(%d,%d,%d)', round(c*255));

%# format color as: #FFFFFF
clr = dec2hex(round(c*255),2)'; clr = ['#';clr(:)]';

%# apply formatting to third row first column
X(3,1) = strcat(...
    ['<html><body bgcolor="' clr '" text="#FF0000" width="100px">'], ...
    X(3,1));

%# display table
f = figure('Position',[100 100 350 150]);
h = uitable('Parent',f, 'ColumnWidth',{100 'auto'}, ...
    'Units','normalized', 'Position',[0.05 0.05 0.9 0.9], ...
    'Data',X, 'ColumnName',{'Name','Rank'}, 'RowName',[]);
Run Code Online (Sandbox Code Playgroud)

截图


注意:我尝试了一些HTML代码的变体.问题是背景颜色仅应用于文本但未填充整个表格单元格:

<html><span style="background-color: #FFFF00; color: #FF0000;">

<html><font style="background-color: #FFFF00; color: #FF0000;">

<html><table cellpadding="0" width="100px" bgcolor="#FFFF00" style="color: #FF0000;"><tr><td>
Run Code Online (Sandbox Code Playgroud)

截图

最后一个工作,但它并不比我之前的代码更好.我尝试了其他CSS技巧来填充整个单元格空间,但失败了.我认为Java Swing组件中支持的HTML/CSS子集是有限的.


上面的HTML方法适用于小表.对于较大的表或当您想要启用编辑时,有一种更好的方法.它需要Java Swing熟悉.