Search code examples
c++chartsc++builderteechart

How can I update data in a chart in execution time (in C++ builder)?


I'm using Borland C++ Builder to create this. The code is very simple because its only purpose, for now, is to help me learn how to use the TChart functions. I'll use what I learn to create a more complex program later.

I have a series of numbers that must be shown on a memo box and on a chart. The values in the chart are displayed after the program finishes its exectuion, however, I need the values to be updated in real time - I mean, everytime the program calculates a new number, it must be immediately show on the chart. Is it possible to do that? If so, how can I do it?

Thanks in advance.

#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{

   TChartSeries* series1 = Chart1->Series[0];
   series1->Clear();

   int num = 0;

   Memo1->Clear();

     for(int i=0; i<5000; i++)
     {
            num = num++;
            Memo1->Lines->Add(IntToStr(num));
            series1->AddXY(i, num, "", clGreen);

           }
   }

Solution

  • You should force a chart repaint whenever you want:

    Chart1->Repaint();
    

    So you could have:

    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
        TChartSeries* series1 = Chart1->Series[0];
        series1->Clear();
    
        int num = 0;
    
        Memo1->Clear();
    
        for(int i=0; i<5000; i++)
        {
            num = num++;
            Memo1->Lines->Add(IntToStr(num));
            series1->AddXY(i, num, "", clGreen);
            Chart1->Repaint();
        }
    }
    

    Or, to improve the performance, you could force a chart repaint after adding some values instead of after each addition. Ie:

    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
        TChartSeries* series1 = Chart1->Series[0];
        series1->Clear();
    
        int num = 0;
    
        Memo1->Clear();
    
        for(int i=0; i<5000; i++)
        {
            num = num++;
            Memo1->Lines->Add(IntToStr(num));
            series1->AddXY(i, num, "", clGreen);
    
            if (i % 100 == 0) {
                Chart1->Repaint();
            }
        }
    }