I have a simple GUI where I want to use a text field to display a constantly changing value generated in a loop. I just don't now how to get it working. From the help files and some forum thread I have the following:
First I create my text object:
hTimer = uicontrol('Style','text','String','Time',...
'Position',[450,300,60,15],...
'Callback',#Timer_CreateFcn);
I create some function:
function Timer_CreateFcn(hObject, eventdata, handles)
global statText
statText = hObject;
end
and then I have have my loop where the values are generated:
while ...
textString=['TestCycleTime = ',num2str(datestr(tsNum(idx-5)-tsNumDoor(1),'MM:SS.FFF')),' [Min:Sec]'];
global statText;
set(statText, 'String', textString);
end
The script is running without errors, but still the timer is not updating.
Could someone please give me a hint?
The issue is that you are updating the 'String' property of your text object within a while loop which prevents MATLAB from automatically taking the time to actually render the change. To alter this behavior, you can explicitly call drawnow after settings the 'String' property to explicitly render the current figure.
set(hTimer, 'String', textString);
drawnow
As a side-note, I would recomment looking into the ways to pass data around your app rather than using global variables.
Related
I'm facing a problem in MATLAB that I don't really know what might be the cause. I have a GUI build with GUIDE on MATLAB R2007b. In this GUI I have a edit used for typing in a file name that is then used for saving some data. I use the edit callback function to test if the file name is valid by checking the string received with get(hObject,'String') on emptyness and then activate/ deactivate the load button if the typed file name exists or not. The string value gets also saved into a variable in the handles structure.
The issue I'm facing now is, that for some reason, the setting of the file name does not work if i type the name 'default' or if the name typed is empty. The statement in the if (isempty(handles.fileName)) block gets executed when nothing is typed in the edit. when default is typed in the string shown in the edit is deleted. Below you can find the code of the callback function.
In the OpeningFcn:
handles.fileName = 'default';
My Callback:
function edit_fileName_Callback(hObject, eventdata, handles)
handles.fileName = get(hObject,'String');
if (isempty(handles.fileName))
handles.fileName = 'default';
disp(handles.fileName)
end
handles.fileName = strrep(handles.fileName,' ','_');
set(hObject,'String',handles.fileName);
if exist(['trajectories/' handles.fileName '.mat'],'file') == 2
set(handles.pushbutton_load,'Enable','on')
else
set(handles.pushbutton_load,'Enable','off')
end
guidata(hObject, handles);
Has someone an idea why this issue might occur? I'm hanging now for quite some time on this issue and have not found yet any solution.
Thanks
Edit 1:
what i found out so far is that the value returned from get(hObject,'String'); and the string coded handles.fileName = 'default'; are not exactly the same. I've added the line disp(['fileName: ' handles.fileName]) to the callback and it shows the a difference with a typed name or when set in the code:
Self typed:
fileName: test
Set by code:
fileName:
default
The coded version somehow adds itself a newline.
Edit 2:
The issue described in Edit 1 was due to a misplacement of the disp command.
Edit 3 / Workaround:
It seems that the string 'default' itself was the cause of trouble. When using another default value it works seamlessly. Furthermore, when 'default' is typed in the field the edit itself does not work properly anymore. seems to be some bug.
I'm creating a uitable in Matlab Guide that generates file names automatically based off of several parameters that a user will enter. For each file name in the table, a run time and number of runs can be specified.
I'm trying to write a callback function for the uitable that will automatically update the run names when either the run time or number of runs is edited. This is the callback function I've written.
function runTableCallback(hObject,callbackdata)
numval = eval(callbackdata.EditData);
r = callbackdata.Indices(1);
c = callbackdata.Indices(2);
if c==2
handles.runnums(r,1)=numval;
hObject.Data{r,c} = numval;
elseif c==3
handles.runtimes(r,1)=numval;
hObject.Data{r,c} = numval;
end
[runlog,runnames,runnums,runtimes,rundesc]=generateRuns(hObject,handles);
handles.runlog=runlog;
handles.runnames=runnames;
handles.runnums=runnums;
handles.runtimes=runtimes;
handles.rundesc=rundesc;
set(handles.uitable19,'Data',[handles.runlog,handles.runnames,handles.runnums,handles.runtimes]);
guidata(hObject, handles);
I need to call the 'generateRuns' funtion in order to create the updated table information with the edited data. Then that updated information will be displayed in the table using the "set" function on the next line. However, I am getting the following error:
Undefined function or variable "handles".
How can I access handles within the callback function? The callback function is specified in the UI Controls for the table in another object callback function.
set(handles.uitable19,'CellEditCallback',#runTableCallback);
Any help would be much appreciated.
You have not passed handles to your callback.
Try adjusting your set call to this:
set(handles.uitable19,'CellEditCallback', {#runTableCallback, handles});
And your function definition to:
function runTableCallback(hObject, callbackdata, handles)
In this post,Matlab: How to get the current mouse position on a click by using callbacks , it shows something as follows:
function mytestfunction()
f=figure;
set(f,'WindowButtonDownFcn',#mytestcallback)
function mytestcallback(hObject,~)
pos=get(hObject,'CurrentPoint');
disp(['You clicked X:',num2str(pos(1)),', Y:',num2str(pos(2))]);
However, I cannot get the pos and use it in mytestfunction().
could anyone help ? Thanks !
If you are not using GUIDE and hence do not have the handles structure (see bottom), you can utilize the UserData property of the figure to pass any information:
set(gcf,'UserData',pos);
Then you can access pos from anywhere else via:
pos = get(gcf,'UserData');
See this MathWorks description of the UserData property, and this full example. From the first page:
All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property's value, but only one value can exist at a time.
As a workaround to this limitation, you could assign a struct to UserData that has all the properties needed by your program stored in different fields.
A detail I left out in the commands above is the figure/object handle (you probably don't actually want to use gcf). In mytestfunction you have it stored in f. In the callback you can find the parent figure of the hObject by:
f = ancestor(hObject,'figure');
One way to use the above approach is to simply wait for changes in the UserData property:
function mytestfunction()
f=figure; set(f,'WindowButtonDownFcn',#mytestcallback)
maxPos=10; cnt=0;
while cnt<maxPos, waitfor(f,'UserData'); pos=get(gcf,'UserData'), cnt=cnt+1; end
function mytestcallback(hObject,~)
pos=get(hObject,'CurrentPoint');
set(ancestor(hObject,'figure'),'UserData',pos);
Note that another way to handle events is to implement a listener to respond to the clicking event, but the WindowButtonDownFcn callback should work fine.
Originally, I was thinking GUIDE, in which you would have the handles structure. This is one purpose of the handles structure. Store the position in a field of handles, and update it:
handles.pos = pos; % store it
guidata(hObject,handles); % update handles in GUI
Then back in mytestfunction or whatever other callback needs access to pos, you can use handles.pos, if the handles structure is up to date.
I created an UItable in Matlab which I fill with various values and options.
It looks like:
the corresponding code is the following:
selector_1 = { 'A'; 'B' ; 'C' };
selector_2 = { 'A.1'; 'A.2'; 'A.3'; ...
'B.1'; 'B.2'; 'B.3'; ...
'C.1'; 'C.2'; 'C.3' };
rows = 5;
f = figure('name','Configuration of output','Position',[200 200 430 25+rows*20],'numbertitle','off','MenuBar','none');
dat = {'select outputfile...', 'select identifier...', 'Specifier', 'Index'};
dat = repmat(dat,rows,1);
columnname = {'Output file ',...
'Identifier ',...
'Specifier ', 'Index'};
columnformat = { {selector_1{:}}, {selector_2{:}}, 'char', 'numeric' };
columneditable = [true true true true];
t = uitable('Units','normalized','Position',...
[0 0 1 1], 'Data', dat,...
'ColumnName', columnname,...
'ColumnFormat', columnformat,...
'ColumnEditable', columneditable,...
'RowName',[]);
set(t, 'Data', dat,'celleditcallback','get(t,''Data'')');
So I run the code and the figure is open. The underlying script has therefore finished.
When I now edit the table my uitable object is changed and after I finished I can get my final configuration with:
finalconfig = get(t,'Data');
But the thing is I need manually type this line, because my script has already finished. If I put this line at the end of my script, I get an error.
So I thought about using the following loop, to detect when I close the table and to store the last configuration
while ~isempty(findobj('name','Configuration of output'))
% some action
end
finalconfig = get(t,'Data');
And I tried everything to put inside the loop, the whole script, just the set command including the celleditcallback, and other things, but nothing worked. Either my script get stucked inside the loop or the display of my table is not updated when I edit a value. I also tried drawnow at different positions. How one handles this situation? How can I automatically store my final results?
I assume "closing the window" is the best action to detect, as I don't think I could implement a "save" button. I also tried to create a gui using GUIDE but got completely lost, I hope to solve it without.
Edit:
I was now able to implement a "save"-button and tried the callback as follows:
uimenu('Label','Save configuration','Callback',#saveConfig);
function saveConfig(~,~)
output = get(t,'Data',);
save([pwd 'output.mat'],'output');
end
also I implemented a custom CloseRequestFcn as suggested by Lucius Domitius Ahenobarbus. But then I have either one of the following problems:
1)
I define everything as a script, everything works fine, but I need to define functions like #saveConfig (actually my favorite) or #my_Closefcn as a unique function-file in my workspace and I have a hard time to pass the right parameters as dat always remains the same, even though it actually gets changend.
(The example from the mathworks site works! But it doesn't need additional parameters.)
2) When I use
function configuration
% my script from above
end
I can implement #saveConfig or #my_Closefcn directly (nested) and I guess the passing of the parameters would work fine. But the editing of my table does not work anymore, throwing the following error:
Error using handle.handle/get
Invalid or deleted object.
Error while evaluating uitable CellEditCallback
How to solve that?
Now that I know that I can even add buttons to an uitable I REALLY like to avoid GUIDE.
My code above is executable, so I'd be glad if you try it to see what my actual problem is, as it is hard to describe.
depending on using GUIDE or not:
use the CloseRequestFcn->
without GUIDE use:
%write your own CloseRequestFcn and set the figure CloseRequest-Callback to it:
set(gcf,'CloseRequestFcn',#my_closefcn)
%use gcf or the handle of the figure directly
and define my_closefcn including a delete statement for the figure-handle, else the figure will not close :)
See the docs for more information about "Redefining the CloseRequestFcn".
with GUIDE:
you can edit the CloseRequestFcn by inspecting the figure. There is a field called CloseRequestFcn that will create the function automatically and you dont need to take care about getting the handle. It will look like this:
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: delete(hObject) closes the figure
delete(hObject);
Now BEFORE deleting the figure, you should be able to get the data of the uitable (if you have the handle) and I would suggest to just assign the data to the base workspace, like:
assignin('base', 'finalTableData', get(myTableHandle,'Data'));
EDIT
as I was not clear enough, see this example:
(use within one single script)->
function test
h=figure;
x=1:10;
mytable=uitable(h,'Data',x);
set(h,'CloseRequestFcn',#myCloseFcn)
%give a unique Tag:
set(h,'Tag', 'myTag')
set(mytable,'Tag','myTableTag')
end
function myCloseFcn(~,~)
myfigure=findobj('Tag','myTag');
myData=get(findobj(myfigure,'Tag','myTableTag'),'Data')
assignin('base','myTestData',myData)
delete(myfigure)
end
in fact, there is no need to take care for the parameters of your Closereq-Callback, if you know how to find the handle of the figure! Just give something to your figure/uitable that you are able to identify it later on. I used 'Tag', because the first thing I would think of, but there would be other parameters as well.
There are only two differences I can think of between running the code directly after the code, or inside the code.
1. Scope
Perhaps you are actually working with functions, rather than scripts. In this case the problem may be that inside your function, something you need is out of scope.
2. Timing
Though it is rare, sometimes the computer may seem to be finished, whilst it is actually still busy (for a few milliseconds or so).
Here are the steps to a general approach:
Make sure there is a trivial line at the place where you want to insert your command (1==1 for example)
Put a breakpoint at the line
Once matlab stops at the breakpoint, wait a second and try to run your command.
If it works I would bet on problem number 2. try placing a pause(1) before your command and see whether it helps.
If it doesn't work you are likely meeting problem number 1. Now it becomes a matter of finding the right place to put your command. And if the command cannot be put somewhere else in the code, perhaps try an ugly evalin(,'base'). However, the latter should really be considered a workaround rather than a solution.
I'm getting this error:
Error in ==> APP>pushbutton2_Callback at 109
img=imread(FileName)
When I try to use FileName in pushbutton2_Callback I'm getting the error mentioned
FileName is variable in pushbutton1_Callback.
You need to pass the variable FileName from one callback to the other. To do this, you can assign the variable to the 'UserData' field of pushbutton1. Your code under pushbutton1_Callback should look something like:
FileName=uigetfile();
set(handles.pushbutton1,'UserData',FileName);
Next, you need to read in the variable under your pushbutton2_Callback:
FileName=get(handles.pushbutton1,'UserData');
img=imread(FileName);
If you want to check your results, you can always leave the semicolons off the end of the lines.
There's a general method to store data with your gui for use between callbacks. You can add arbitrary fields to the handles object, so you can put in your pushbutton1 callback
handles.filename = FileName;
guidata(hObject,handles);
The second line is boilerplate code that you need to put at the end of any callback that changes values in the handles structure.
Now all of your callbacks will have access to the file name. In your specific case, in callback 2, you would have
img = imread(handles.filename);
Of course, you might want to use this image later on in another function, so you can store it in handles too
handles.img = img;
guidata(hObject, handles);