Using a Timer to Repaint GUI


#1

Is using a timer to repaint the GUI at specific intervals the best approach? I’m trying to repaint my GUI component every x milliseconds.

I’m currently running into some issues. I need to send in a reference to my GUI component into my Timer constructor so that way I can access the the repaint function of my GUI component. So I need to include that GUI component in the header of my Timer, but I need to include the Timer in the header of my GUI component, so that I can use it. Using this method, Id have to use forward declaration in order to avoid an endless loop of includes, or a macro,

Is there a better way to have access to the repaint method from the Timer? Or even a totally different method?

Thanks.


#2

Maybe make your Timer subclass have a std::function member that you initialize with a lambda that does the repainting…?


#3
class MyComp : public Component : public Timer
{
public:
  MyComp()
  {
     startTimer(100)
  };

  void timerCallback() override
  { 
    repaint()
  };

  void paint(Graphics &g) override
  {
  // paint here
  };

};

#4

An alternate option is to use the AsyncUpdater class and in the callback handler call repaint()… then in your variable setter triggerAsyncUpdate().

Another option is to use MessageManager::callAsync() but if you do make sure of the lifetime of the target object.

Rail


#5

to overcomplicate even further:

class MyComp : public Component, public Timer, public AsyncUpdater
{
public:
  MyComp()
  {
     startTimer(100)
  };

  void timerCallback() override
  { 
    triggerAsyncUpdate();
  }

  void handleAsyncUpdate() override
  {
    repaint();
  }

  void paint(Graphics &g) override
  {
  // paint here
  }

};

#6

Oh no, never use a Timer to trigger an AsyncUpdater - there’s no point, it’d just add the overhead of sending a second message without any advantage at all.


#7

right, that’s why I said “to overcomplicate even further”


#8

Sure, but when beginners see a lump of code, they tend to copy-paste without understanding it.

So I’m just clarifying for their benefit that the simplest approach is what chkn posted above (but without those horrible semicolons-at-the-end-of-functions!)


#9

since you’re here on the forum today, could ya take a look at this weird OS X memory leak?


#10

Amazing, I never even considered simply inheriting the Timer class… jeez, here I am making my own Timer class and inheriting Timer into it so I can implement the callback function, when I simply could’ve just let my GUI component inherit Timer. Such a simple solution. Thanks a ton.


#11

Understandable, but I do my best to never use code suggestions without trying to understand them first.