English Русский
preview
Tablas en el paradigma MVC en MQL5: Tabla de correlación de símbolos

Tablas en el paradigma MVC en MQL5: Tabla de correlación de símbolos

MetaTrader 5 — Ejemplos |
32 0
Artyom Trishkin
Artyom Trishkin

Índice


Introducción

En el artículo anterior, dedicado a la creación de tablas en el marco del paradigma MVC, ampliamos las funcionalidades de las tablas añadiendo la posibilidad de ajustar el ancho de las columnas, especificar los tipos de datos que se muestran y ordenar los datos por columnas. Estas mejoras han hecho que las tablas sean más flexibles y fáciles de manejar con distintos conjuntos de datos. Sin embargo, para algunas tareas que requieren presentar los datos con una referencia clara a las filas, se necesita un elemento adicional de la interfaz: un encabezado vertical que muestre los encabezados de fila.

Hoy no vamos a recurrir a ejemplos abstractos de tablas, sino que vamos a crear un ejemplo práctico de un indicador para generar una tabla de correlación simétrica de los símbolos seleccionados en la configuración, en la que el encabezado vertical y el encabezado horizontal mostrarán los nombres de los símbolos, y la propia tabla mostrará los valores de correlación entre ellos. Para ello, añadiremos a la tabla un encabezado vertical que, en general, contendrá etiquetas para las filas, por ejemplo, sus números de orden u otros identificadores, y en el caso del ejemplo elegido, los nombres de los símbolos. La presencia de dos encabezados en la tabla facilitará la interpretación de los datos, especialmente al trabajar con tablas en las que las filas tienen un significado importante.

Para implementar dicha funcionalidad, modificaremos las clases existentes añadiendo soporte para el encabezado vertical y garantizaremos una interacción correcta entre los componentes dentro del paradigma MVC. El resultado será una herramienta que no solo mejorará la vista de los datos, sino que también facilitará su análisis.


Mejoras en las clases de la biblioteca

Todos los archivos del proyecto se encuentran en la ruta \MQL5\Indicators\Tables\. El archivo de clases del modelo de tabla (Tables.mqh), junto con el archivo del indicador de prueba (iCorrelationTable.mq5), se encuentra en la carpeta \MQL5\Indicators\Tables\.

Los archivos de la biblioteca gráfica (Base.mqh y Controls.mqh) se encuentran en la subcarpeta \MQL5\Indicators\Tables\Controls\. Todos los archivos necesarios para el trabajo se pueden descargar en un único archivo comprimido desde el artículo anterior.

Hoy modificaremos la clase base de la biblioteca gráfica \MQL5\Indicators\Tables\Controls\Base.mqh.

Así, añadiremos la declaración anticipada de las nuevas clases y las enumeraciones de los nuevos tipos de objetos:

//+------------------------------------------------------------------+
//| Included libraries                                               |
//+------------------------------------------------------------------+
#include <Canvas\Canvas.mqh>              // CCanvas
#include <Arrays\List.mqh>                // CList
#include "..\Tables.mqh"

//--- Forward declarations for control classes
class    CBoundedObj;                     // Base class that stores an object's dimensions
class    CCanvasBase;                     // Base class for the canvas of graphical elements
class    CCounter;                        // Delay counter class
class    CAutoRepeat;                     // Event auto-repeat class
class    CImagePainter;                   // Image drawing class
class    CVisualHint;                     // Tooltip class
class    CLabel;                          // Text label class
class    CButton;                         // Simple button class
class    CButtonTriggered;                // Two-state button class
class    CButtonArrowUp;                  // Up-arrow button class
class    CButtonArrowDown;                // Down-arrow button class
class    CButtonArrowLeft;                // Left-arrow button class
class    CButtonArrowRight;               // Right-arrow button class
class    CCheckBox;                       // CheckBox control class
class    CRadioButton;                    // RadioButton control class
class    CScrollBarThumbH;                // Horizontal scrollbar slider class
class    CScrollBarThumbV;                // Vertical scrollbar slider class
class    CScrollBarH;                     // Horizontal scrollbar class
class    CScrollBarV;                     // Vertical scrollbar class
class    CTableCellView;                  // Table cell visual representation class
class    CTableRowView;                   // Table row visual representation class
class    CCaptionView;                    // Base object class for a header visual representation
class    CColumnCaptionView;              // Table column header visual representation class
class    CRowCaptionView;                 // Table row header visual representation class
class    CTableHeaderView;                // Table header visual representation class
class    CTableRowsHeaderView;            // Visual representation class for table row headers
class    CTableView;                      // Table visual representation class
class    CTableControl;                   // Table management class
class    CPanel;                          // Panel control class
class    CGroupBox;                       // GroupBox control class
class    CContainer;                      // Container control class

//+------------------------------------------------------------------+
//| Macro substitutions                                              |
//+------------------------------------------------------------------+
#define  clrNULL              0x00FFFFFF  // Transparent color for CCanvas
#ifndef  __TABLES__
#define  MARKER_START_DATA    -1          // Data start marker in the file
#endif 
#define  DEF_FONTNAME         "Calibri"   // Default font
#define  DEF_FONTSIZE         10          // Default font size
#define  DEF_EDGE_THICKNESS   3           // Area width for capturing border/corner

//+------------------------------------------------------------------+
//| Enumerations                                                     |
//+------------------------------------------------------------------+
enum ENUM_ELEMENT_TYPE                    // Enumeration of graphical element types
  {
   ELEMENT_TYPE_BASE = 0x10000,           // Base object for graphical elements
   ELEMENT_TYPE_COLOR,                    // Color object
   ELEMENT_TYPE_COLORS_ELEMENT,           // Color set object for a graphical object element
   ELEMENT_TYPE_RECTANGLE_AREA,           // Rectangular area of an element
   ELEMENT_TYPE_IMAGE_PAINTER,            // Object for drawing images
   ELEMENT_TYPE_COUNTER,                  // Counter object
   ELEMENT_TYPE_AUTOREPEAT_CONTROL,       // Event auto-repeat object
   ELEMENT_TYPE_BOUNDED_BASE,             // Base object for graphical element dimensions
   ELEMENT_TYPE_CANVAS_BASE,              // Base canvas object for graphical elements
   ELEMENT_TYPE_ELEMENT_BASE,             // Base object for graphical elements
   ELEMENT_TYPE_HINT,                     // Tooltip
   ELEMENT_TYPE_LABEL,                    // Text label
   ELEMENT_TYPE_BUTTON,                   // Simple button
   ELEMENT_TYPE_BUTTON_TRIGGERED,         // Two-state button
   ELEMENT_TYPE_BUTTON_ARROW_UP,          // Up arrow button
   ELEMENT_TYPE_BUTTON_ARROW_DOWN,        // Down arrow button
   ELEMENT_TYPE_BUTTON_ARROW_LEFT,        // Left arrow button
   ELEMENT_TYPE_BUTTON_ARROW_RIGHT,       // Right arrow button
   ELEMENT_TYPE_CHECKBOX,                 // CheckBox control
   ELEMENT_TYPE_RADIOBUTTON,              // RadioButton control
   ELEMENT_TYPE_SCROLLBAR_THUMB_H,        // Horizontal scrollbar thumb
   ELEMENT_TYPE_SCROLLBAR_THUMB_V,        // Vertical scrollbar thumb
   ELEMENT_TYPE_SCROLLBAR_H,              // ScrollBarHorisontal control
   ELEMENT_TYPE_SCROLLBAR_V,              // ScrollBarVertical control
   ELEMENT_TYPE_TABLE_CELL_VIEW,          // Table cell (view)
   ELEMENT_TYPE_TABLE_ROW_VIEW,           // Table row (view)
   ELEMENT_TYPE_TABLE_CAPTION_VIEW,       // Base header object (view)
   ELEMENT_TYPE_TABLE_COLUMN_CAPTION_VIEW,// Table column header (view)
   ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW,   // Table row header (view)
   ELEMENT_TYPE_TABLE_HEADER_VIEW,        // Table header (view)
   ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW,   // Table row header (view)
   ELEMENT_TYPE_TABLE_VIEW,               // Table (view)
   ELEMENT_TYPE_TABLE_CONTROL_VIEW,       // Table control (view)
   ELEMENT_TYPE_PANEL,                    // Panel control
   ELEMENT_TYPE_GROUPBOX,                 // GroupBox control
   ELEMENT_TYPE_CONTAINER,                // Container control
  };

En la función que devuelve el nombre abreviado de un elemento según su tipo, introduciremos los nuevos nombres para los nuevos elementos:

//+------------------------------------------------------------------+
//|  Return the short name of an element by type                     |
//+------------------------------------------------------------------+
string ElementShortName(const ENUM_ELEMENT_TYPE type)
  {
   switch(type)
     {
      case ELEMENT_TYPE_ELEMENT_BASE               :  return "BASE";    // Base object for graphical elements
      case ELEMENT_TYPE_HINT                       :  return "HNT";     // Tooltip
      case ELEMENT_TYPE_LABEL                      :  return "LBL";     // Text label
      case ELEMENT_TYPE_BUTTON                     :  return "SBTN";    // Simple button
      case ELEMENT_TYPE_BUTTON_TRIGGERED           :  return "TBTN";    // Two-state button
      case ELEMENT_TYPE_BUTTON_ARROW_UP            :  return "BTARU";   // Up arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_DOWN          :  return "BTARD";   // Down arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_LEFT          :  return "BTARL";   // Left arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_RIGHT         :  return "BTARR";   // Right arrow button
      case ELEMENT_TYPE_CHECKBOX                   :  return "CHKB";    // CheckBox control
      case ELEMENT_TYPE_RADIOBUTTON                :  return "RBTN";    // RadioButton control
      case ELEMENT_TYPE_SCROLLBAR_THUMB_H          :  return "THMBH";   // Horizontal scrollbar slider
      case ELEMENT_TYPE_SCROLLBAR_THUMB_V          :  return "THMBV";   // Vertical scrollbar slider
      case ELEMENT_TYPE_SCROLLBAR_H                :  return "SCBH";    // ScrollBarHorisontal control
      case ELEMENT_TYPE_SCROLLBAR_V                :  return "SCBV";    // ScrollBarVertical control
      case ELEMENT_TYPE_TABLE_CELL_VIEW            :  return "TCELL";   // Table cell (view)
      case ELEMENT_TYPE_TABLE_ROW_VIEW             :  return "TROW";    // Table row (view)
      case ELEMENT_TYPE_TABLE_CAPTION_VIEW         :  return "TCAPT";   // Base header object (view)
      case ELEMENT_TYPE_TABLE_COLUMN_CAPTION_VIEW  :  return "TCCAPT";  // Table column header (view)
      case ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW     :  return "TRCAPT";  // Table row header (view)
      case ELEMENT_TYPE_TABLE_HEADER_VIEW          :  return "TCHDR";   // Table header (view)
      case ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW     :  return "TRHDR";   // Table row headers (view)
      case ELEMENT_TYPE_TABLE_VIEW                 :  return "TABLE";   // Table (view)
      case ELEMENT_TYPE_TABLE_CONTROL_VIEW         :  return "TBLCTRL"; // Table control (view)
      case ELEMENT_TYPE_PANEL                      :  return "PNL";     // Panel control
      case ELEMENT_TYPE_GROUPBOX                   :  return "GRBX";    // GroupBox control
      case ELEMENT_TYPE_CONTAINER                  :  return "CNTR";    // Container control
      default                                      :  return "Unknown"; // Unknown
     }
  }

En la clase CColorElement, que gestiona los colores de un elemento de un objeto gráfico, declararemos un nuevo método que devolverá un color interpolado entre tres colores en función del valor del coeficiente:

//+------------------------------------------------------------------+
//| Class for graphical object element colors                        |
//+------------------------------------------------------------------+
class CColorElement : public CBaseObj
  {
protected:
   CColor            m_current;                                // Current color. Can be one of the following
   CColor            m_default;                                // Normal-state color
   CColor            m_focused;                                // Hover-state color
   CColor            m_pressed;                                // Pressed-state color
   CColor            m_blocked;                                // Disabled element color
   
//--- Convert RGB to color
   color             RGBToColor(const double r,const double g,const double b) const;
//--- Write the RGB component values to variables
   void              ColorToRGB(const color clr,double &r,double &g,double &b);
//--- Return the color component: (1) Red, (2) Green, (3) Blue
   double            GetR(const color clr)                     { return clr&0xFF;                           }
   double            GetG(const color clr)                     { return(clr>>8)&0xFF;                       }
   double            GetB(const color clr)                     { return(clr>>16)&0xFF;                      }
   
public:
//--- Return a new color
   color             NewColor(color base_color, int shift_red, int shift_green, int shift_blue);

//--- Returns an interpolated color between three colors depending on the coefficient value (from -1 to +1)
   color             InterpolateColorByCoeff(const color color1, const color color2, const color color3, const double coeff);

//--- Class initialization
   void              Init(void);

//--- Initialize colors for different states
   bool              InitDefault(const color clr)              { return this.m_default.SetColor(clr);       }
   bool              InitFocused(const color clr)              { return this.m_focused.SetColor(clr);       }
   bool              InitPressed(const color clr)              { return this.m_pressed.SetColor(clr);       }
   bool              InitBlocked(const color clr)              { return this.m_blocked.SetColor(clr);       }
   
//--- Set colors for all states
   void              InitColors(const color clr_default, const color clr_focused, const color clr_pressed, const color clr_blocked);
   void              InitColors(const color clr);
    
//--- Return colors for different states
   color             GetCurrent(void)                    const { return this.m_current.Get();               }
   color             GetDefault(void)                    const { return this.m_default.Get();               }
   color             GetFocused(void)                    const { return this.m_focused.Get();               }
   color             GetPressed(void)                    const { return this.m_pressed.Get();               }
   color             GetBlocked(void)                    const { return this.m_blocked.Get();               }
   
//--- Set one of the colors from the list as the current color
   bool              SetCurrentAs(const ENUM_COLOR_STATE color_state);

//--- Return a description of the object
   virtual string    Description(void);
   
//--- Virtual methods for (1) saving to a file, (2) loading from a file, and (3) object type
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                          const { return(ELEMENT_TYPE_COLORS_ELEMENT);       }
   
//--- Constructors/destructor
                     CColorElement(void);
                     CColorElement(const color clr);
                     CColorElement(const color clr_default,const color clr_focused,const color clr_pressed,const color clr_blocked);
                    ~CColorElement(void) {}
  };

Fuera del cuerpo de la clase, escribiremos su implementación:

//+------------------------------------------------------------------+
//| Return an interpolated color between three colors                |
//| depending on the coefficient value (from -1 to +1)               |
//+------------------------------------------------------------------+
color CColorElement::InterpolateColorByCoeff(const color color1,const color color2,const color color3,const double coeff)
  {
//--- Limit the coefficient value
   double val=::fmax(-1.0,::fmin(1.0,coeff));

//--- Variables for obtaining the RGB components of each color
   double r1, g1, b1, r2, g2, b2;
   double r, g, b, t;

//--- Interpolation between the initial and middle colors
   if(val<0.0)
     {
      this.ColorToRGB(color1,r1,g1,b1);
      this.ColorToRGB(color2,r2,g2,b2);
      t=(val+1.0)/1.0;
      r=r1+(r2-r1)*t;
      g=g1+(g2-g1)*t;
      b=b1+(b2-b1)*t;
     }
//--- Interpolation between the middle and final colors
   else
     {
      this.ColorToRGB(color3,r1,g1,b1); 
      this.ColorToRGB(color2,r2,g2,b2);
      t=val/1.0;
      r=r2+(r1-r2)*t;
      g=g2+(g1-g2)*t;
      b=b2+(b1-b2)*t;
     }
//--- Return the calculated color
   return this.RGBToColor(r,g,b);
  }

El método calcula el color interpolado a partir de tres colores especificados (color1, color2, color3) y el coeficiente coeff. El primer color es el que corresponde al valor del coeficiente -1. El segundo color es el que corresponde al valor del coeficiente 0; el último color es el que corresponde al valor del coeficiente +1. Como los valores de correlación entre los símbolos oscilan entre -1 y +1, este método permitirá calcular de forma continua el valor del color de una celda a partir del valor del coeficiente (de correlación entre los símbolos) y devolverá el color calculado.

En el manejador de eventos de la clase base CCanvasBase, incluiremos el control del tamaño de la subventana del gráfico:

//+------------------------------------------------------------------+
//| CCanvasBase::Event handler                                       |
//+------------------------------------------------------------------+
void CCanvasBase::OnChartEvent(const int id,const long& lparam,const double& dparam,const string& sparam)
  {
//--- If the height of the indicator subwindow has not yet been determined when the terminal starts,
//--- we will adjust the distance between the top border of the indicator subwindow and the top border of the main chart window
   if(this.m_wnd>0 && this.m_wnd_y==0)
      this.m_wnd_y=(int)::ChartGetInteger(this.m_chart_id,CHART_WINDOW_YDISTANCE,this.m_wnd);

//--- Chart change event
//...
//...

Cuando el terminal se inicia con un indicador instalado en una subventana, es posible que el tamaño de la subventana aún no se haya obtenido al inicializar las clases y que la distancia entre el borde superior de la subventana del indicador y el borde superior de la ventana principal siga siendo cero. Esto impide realizar un seguimiento correcto de la posición del cursor (sus coordenadas se leen desde la ventana principal del gráfico, y no desde la subventana). Al añadir el fragmento de código indicado, se soluciona este problema.

Ahora crearemos nuevas clases para el encabezado vertical de la tabla en el archivo \MQL5\Indicators\Tables\Controls\Controls.mqh.

En la sección de sustitución de macros, definiremos la anchura mínima de los encabezados de fila de la tabla, y en la sección de enumeraciones añadiremos una nueva enumeración que defina los modos de resaltado de las filas o celdas de la tabla:

//+------------------------------------------------------------------+
//| Included libraries                                               |
//+------------------------------------------------------------------+
#include "Base.mqh"

//+------------------------------------------------------------------+
//| Macro substitutions                                              |
//+------------------------------------------------------------------+
#define  DEF_LABEL_W                50          // Default text label width
#define  DEF_LABEL_H                16          // Default text label height
#define  DEF_BUTTON_W               60          // Default button width
#define  DEF_BUTTON_H               16          // Default button height
#define  DEF_TABLE_ROW_H            16          // Default table row height
#define  DEF_TABLE_HEADER_H         20          // Default table header height
#define  DEF_TABLE_ROWS_HEADER_W    24          // Minimum width of the table row headers
#define  DEF_TABLE_COLUMN_MIN_W     12          // Minimum width of the table column
#define  DEF_PANEL_W                80          // Default panel width
#define  DEF_PANEL_H                80          // Default panel height
#define  DEF_PANEL_MIN_W            60          // Minimum panel width
#define  DEF_PANEL_MIN_H            60          // Minimum panel height
#define  DEF_SCROLLBAR_TH           13          // Default scrollbar width
#define  DEF_THUMB_MIN_SIZE         8           // Minimum width of the scrollbar thumb
#define  DEF_AUTOREPEAT_DELAY       500         // Delay before launching the auto-repeat
#define  DEF_AUTOREPEAT_INTERVAL    100         // Auto-repeat frequency

#define  DEF_HINT_NAME_TOOLTIP      "HintTooltip"     // "Tooltip" name
#define  DEF_HINT_NAME_HORZ         "HintHORZ"        // "Double horizontal arrow" tooltip name
#define  DEF_HINT_NAME_VERT         "HintVERT"        // "Double vertical arrow" tooltip name
#define  DEF_HINT_NAME_NWSE         "HintNWSE"        // "Double upper-left arrow" --- bottom right (NorthWest-SouthEast) tooltip name
#define  DEF_HINT_NAME_NESW         "HintNESW"        // "Double bottom-left arrow" --- upper right (NorthEast-SouthWest) tooltip name
#define  DEF_HINT_NAME_SHIFT_HORZ   "HintShiftHORZ"   // "Horizontal shift arrow" tooltip name
#define  DEF_HINT_NAME_SHIFT_VERT   "HintShiftVERT"   // "Vertical shift arrow" tooltip name

//+------------------------------------------------------------------+
//| Enumerations                                                     |
//+------------------------------------------------------------------+
enum ENUM_ELEMENT_SORT_BY                       // Compared properties
  {
   ELEMENT_SORT_BY_ID   =  BASE_SORT_BY_ID,     // Comparison by element ID
   ELEMENT_SORT_BY_NAME =  BASE_SORT_BY_NAME,   // Comparison by element name
   ELEMENT_SORT_BY_X    =  BASE_SORT_BY_X,      // Comparison by element X-coordinate
   ELEMENT_SORT_BY_Y    =  BASE_SORT_BY_Y,      // Comparison by element Y-coordinate
   ELEMENT_SORT_BY_WIDTH=  BASE_SORT_BY_WIDTH,  // Comparison by element width
   ELEMENT_SORT_BY_HEIGHT= BASE_SORT_BY_HEIGHT, // Comparison by element height
   ELEMENT_SORT_BY_ZORDER= BASE_SORT_BY_ZORDER, // Comparison by element Z-order
   ELEMENT_SORT_BY_TEXT,                        // Comparison by element text
   ELEMENT_SORT_BY_COLOR_BG,                    // Comparison by element background color
   ELEMENT_SORT_BY_ALPHA_BG,                    // Comparison by element background transparency
   ELEMENT_SORT_BY_COLOR_FG,                    // Comparison by the element foreground color
   ELEMENT_SORT_BY_ALPHA_FG,                    // Comparison by the element foreground transparency
   ELEMENT_SORT_BY_STATE,                       // Comparison by element state
   ELEMENT_SORT_BY_GROUP,                       // Comparison by element group
  };

enum ENUM_TABLE_SORT_MODE                       // Table column sorting modes
  {
   TABLE_SORT_MODE_NONE,                        // No sorting
   TABLE_SORT_MODE_ASC,                         // Ascending sorting
   TABLE_SORT_MODE_DESC,                        // Descending sorting
  };

enum ENUM_HINT_TYPE                             // Tooltip types
  {
   HINT_TYPE_TOOLTIP,                           // Tooltip
   HINT_TYPE_ARROW_HORZ,                        // Double horizontal arrow
   HINT_TYPE_ARROW_VERT,                        // Double vertical arrow
   HINT_TYPE_ARROW_NWSE,                        // Double arrow from top left to bottom right (NorthWest-SouthEast)
   HINT_TYPE_ARROW_NESW,                        // Double arrow bottom left --- top right (NorthEast-SouthWest)
   HINT_TYPE_ARROW_SHIFT_HORZ,                  // Horizontal displacement arrow
   HINT_TYPE_ARROW_SHIFT_VERT,                  // Vertical displacement arrow
  };

enum ENUM_ROWS_HIGHLIGHT_MODE                   // Table row/cell highlighting modes
  {
   ROWS_HIGHLIGHT_MODE_CELLS,                   // Highlight individual cells (cell mode)
   ROWS_HIGHLIGHT_MODE_ROW,                     // Highlight the entire row (row mode)
  };  

Si bien todo está claro en cuanto a la anchura mínima del encabezado, conviene aclarar lo relativo al modo de resaltado de las filas o celdas: las filas de tabla son elementos gráficos del tipo "Panel". Este elemento tiene su propio manejador de eventos para el paso del cursor del ratón sobre él: por defecto, el color del elemento se vuelve ligeramente más claro. Cada fila de tabla tiene su propia lista de celdas, que se encuentran en esa fila. La enumeración indica cómo gestionar el evento de paso del cursor sobre una fila: o bien toda la fila se aclara ligeramente, o bien cada celda puede resaltarse cambiando su propio color.

Por el momento, solo funciona plenamente la primera opción, que ya se había implementado anteriormente. En la segunda opción, el manejador de eventos simplemente está desactivado. Pero será precisamente la segunda opción la que se aplicará a las filas de tabla, en las que cada celda se coloreará con su propio color, en función del valor de correlación entre los símbolos de dicha celda. Para evitar parpadeos innecesarios de la fila, usaremos la segunda opción, que simplemente no modifica el color. Más adelante, esta opción podría perfeccionarse, de modo que cada celda cuente con su propio manejador de eventos para el paso del cursor sobre ella.

De momento, la tabla solo tiene un encabezado, el horizontal, en el que se encuentran los encabezados de columna. Todo esto se organiza en dos clases:

  1. CColumnCaptionView: encabezado de columna,
  2. CTableHeaderView: encabezado horizontal de la tabla que contiene una lista de objetos de encabezado de columna.

Ahora tenemos que reorganizar esta estructura, ya que también tendremos un encabezado vertical en la tabla. Al igual que el encabezado horizontal, contendrá una lista de objetos de encabezado de fila.

Por tanto, necesitaremos otra clase de encabezado, para el encabezado de fila, y una clase de encabezado vertical. En consecuencia, la estructura de clases será más ramificada: crearemos una clase abstracta común de encabezado con las propiedades compartidas por todos los encabezados, tanto de columna como de fila, mientras que las clases derivadas tendrán las propiedades y los métodos específicos de cada tipo de encabezado:

  1. CCaptionView: objeto base de encabezado
    • CColumnCaptionView: clase de objeto de encabezado de columna que hereda de CCaptionView,
    • CRowCaptionView: clase de objeto de encabezado de fila que hereda de CCaptionView.
  2. CTableHeaderView: encabezado horizontal de la tabla, que contiene una lista de encabezados de columna CColumnCaptionView,
  3. CTableRowsHeaderView: encabezado vertical de la tabla que contiene una lista de encabezados de fila CRowCaptionView.

En el método de creación de un elemento de la lista de la clase CListElm, definiremos la creación de objetos de nuevas clases:

//+------------------------------------------------------------------+
//| Method for creating a list element                               |
//+------------------------------------------------------------------+
CObject *CListElm::CreateElement(void)
  {
//--- Depending on the object type in m_element_type, create a new object
   switch(this.m_element_type)
     {
      case ELEMENT_TYPE_BASE                       :  return new CBaseObj();           // Base object for graphical elements
      case ELEMENT_TYPE_COLOR                      :  return new CColor();             // Color object
      case ELEMENT_TYPE_COLORS_ELEMENT             :  return new CColorElement();      // Color set object for a graphical object element
      case ELEMENT_TYPE_RECTANGLE_AREA             :  return new CBound();             // Rectangular area of the element
      case ELEMENT_TYPE_IMAGE_PAINTER              :  return new CImagePainter();      // An object for drawing images
      case ELEMENT_TYPE_CANVAS_BASE                :  return new CCanvasBase();        // Base canvas object for graphical elements
      case ELEMENT_TYPE_ELEMENT_BASE               :  return new CElementBase();       // Base object for graphical elements
      case ELEMENT_TYPE_HINT                       :  return new CVisualHint();        // Tooltip
      case ELEMENT_TYPE_LABEL                      :  return new CLabel();             // Text label
      case ELEMENT_TYPE_BUTTON                     :  return new CButton();            // Simple button
      case ELEMENT_TYPE_BUTTON_TRIGGERED           :  return new CButtonTriggered();   // Two-state button
      case ELEMENT_TYPE_BUTTON_ARROW_UP            :  return new CButtonArrowUp();     // Up arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_DOWN          :  return new CButtonArrowDown();   // Down arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_LEFT          :  return new CButtonArrowLeft();   // Left arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_RIGHT         :  return new CButtonArrowRight();  // Right arrow button
      case ELEMENT_TYPE_CHECKBOX                   :  return new CCheckBox();          // CheckBox control
      case ELEMENT_TYPE_RADIOBUTTON                :  return new CRadioButton();       // RadioButton control
      case ELEMENT_TYPE_TABLE_CELL_VIEW            :  return new CTableCellView();     // Table cell (View)
      case ELEMENT_TYPE_TABLE_ROW_VIEW             :  return new CTableRowView();      // Table row (View)
      case ELEMENT_TYPE_TABLE_CAPTION_VIEW         :  return new CCaptionView();       // Base header object (View)
      case ELEMENT_TYPE_TABLE_COLUMN_CAPTION_VIEW  :  return new CColumnCaptionView(); // Table column header (View)
      case ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW     :  return new CRowCaptionView();    // Table row header (View)
      case ELEMENT_TYPE_TABLE_HEADER_VIEW          :  return new CTableHeaderView();   // Table header (View)
      case ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW     :  return new CTableRowsHeaderView();// Vertical table header (View)
      case ELEMENT_TYPE_TABLE_VIEW                 :  return new CTableView();         // Table (View)
      case ELEMENT_TYPE_PANEL                      :  return new CPanel();             // Panel control
      case ELEMENT_TYPE_GROUPBOX                   :  return new CGroupBox();          // GroupBox control
      case ELEMENT_TYPE_CONTAINER                  :  return new CContainer();         // GroupBox control
      default                                      :  return NULL;
     }
  }

Si observamos una tabla de Excel, en la intersección del encabezado horizontal y el encabezado vertical, en la esquina superior izquierda de la tabla, veremos un icono triangular en la esquina inferior derecha de la zona donde se cruzan ambos encabezados:

Vamos a hacer uno igual.

Todos nuestros dibujos se crean mediante una clase especial para dibujar, llamada CImagePainter.

Declararemos en la clase los métodos para dibujar triángulos situados en cada una de las esquinas de una región rectangular:

//+------------------------------------------------------------------+
//| Image drawing class                                              |
//+------------------------------------------------------------------+
class CImagePainter : public CBaseObj
  {
protected:
   CCanvas          *m_canvas;                                 // Pointer to the canvas we draw on
   CBound            m_bound;                                  // Image coordinates and boundaries
   uchar             m_alpha;                                  // Transparency
   
//--- Check the validity of the canvas and the correctness of its dimensions
   bool              CheckBound(const string source);

public:
//--- (1) Assign the canvas for drawing, (2) set and (3) return the transparency
   void              CanvasAssign(CCanvas *canvas)             { this.m_canvas=canvas;                }
   void              SetAlpha(const uchar value)               { this.m_alpha=value;                  }
   uchar             Alpha(void)                         const { return this.m_alpha;                 }
   
//--- (1) Set the coordinates and (2) resize the area
   void              SetXY(const int x,const int y)            { this.m_bound.SetXY(x,y);             }
   void              SetSize(const int w,const int h)          { this.m_bound.Resize(w,h);            }
//--- Set the coordinates and dimensions of the area
   void              SetBound(const int x,const int y,const int w,const int h)
                       {
                        this.SetXY(x,y);
                        this.SetSize(w,h);
                       }

//--- Return the bounds and dimensions of the drawing
   int               X(void)                             const { return this.m_bound.X();             }
   int               Y(void)                             const { return this.m_bound.Y();             }
   int               Right(void)                         const { return this.m_bound.Right();         }
   int               Bottom(void)                        const { return this.m_bound.Bottom();        }
   int               Width(void)                         const { return this.m_bound.Width();         }
   int               Height(void)                        const { return this.m_bound.Height();        }
   
//--- Clear the area
   bool              Clear(const int x,const int y,const int w,const int h,const bool update=true);
//--- Draw a filled arrow (1) up, (2) down, (3) left, (4) right
   bool              ArrowUp(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              ArrowDown(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              ArrowLeft(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              ArrowRight(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   
//--- Draw (1) a horizontal 17×7 and (2) a vertical 7×17 double arrow
   bool              ArrowHorz(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true); 
   bool              ArrowVert(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true); 
   
//--- Draw a diagonal 17×17 double arrow (1) from the top left --- to the bottom right, (2) from the bottom left --- to the top right
   bool              ArrowNWSE(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              ArrowNESW(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   
//--- Draw an 18×18 offset arrow (1) horizontally, (2) vertically
   bool              ArrowShiftHorz(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              ArrowShiftVert(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   
//--- Draw (1) a checked, (2) an unchecked CheckBox
   bool              CheckedBox(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              UncheckedBox(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   
//--- Draw (1) a selected, (2) an unselected RadioButton
   bool              CheckedRadioButton(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              UncheckedRadioButton(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);

//--- Draw a border around a group of elements
   bool              FrameGroupElements(const int x,const int y,const int w,const int h,const string text,
                                        const color clr_text,const color clr_dark,const color clr_light,
                                        const uchar alpha,const bool update=true);
   
//--- Draw a filled triangle in (1) the upper-left corner, (2) the lower-left corner, (3) the upper-right corner, and (4) the lower-right corner
   bool              TriangleLT(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              TriangleLB(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              TriangleRT(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);
   bool              TriangleRB(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true);

//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0) const;
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                          const { return(ELEMENT_TYPE_IMAGE_PAINTER);  }
   
//--- Constructors/destructor
                     CImagePainter(void) : m_canvas(NULL)               { this.SetBound(1,1,DEF_BUTTON_H-2,DEF_BUTTON_H-2); this.SetName("Image Painter");  }
                     CImagePainter(CCanvas *canvas) : m_canvas(canvas)  { this.SetBound(1,1,DEF_BUTTON_H-2,DEF_BUTTON_H-2); this.SetName("Image Painter");  }
                     CImagePainter(CCanvas *canvas,const int id,const string name) : m_canvas(canvas)
                       {
                        this.m_id=id;
                        this.SetName(name);
                        this.SetBound(1,1,DEF_BUTTON_H-2,DEF_BUTTON_H-2);
                       }
                     CImagePainter(CCanvas *canvas,const int id,const int dx,const int dy,const int w,const int h,const string name) : m_canvas(canvas)
                       {
                        this.m_id=id;
                        this.SetName(name);
                        this.SetBound(dx,dy,w,h);
                       }
                    ~CImagePainter(void) {}
  };

Fuera del cuerpo de la clase, escribiremos su implementación:

//+------------------------------------------------------------------+
//| Draw a filled triangle in the upper-left corner                  |
//+------------------------------------------------------------------+
bool CImagePainter::TriangleLT(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true)
  {
//--- If the image area is invalid, return false
   if(!this.CheckBound(__FUNCTION__))
      return false;

//--- Shape coordinates
   int x1=x;
   int y1=y+h;
   int x2=x1;
   int y2=y;
   int x3=x2+w;
   int y3=y2;
   
//--- Draw a triangle
   this.m_canvas.FillTriangle(x1,y1,x2,y2,x3,y3,::ColorToARGB(clr,alpha));

   if(update)
      this.m_canvas.Update(false);
   return true;
  }
//+------------------------------------------------------------------+
//| Draw a filled triangle in the lower-left corner                  |
//+------------------------------------------------------------------+
bool CImagePainter::TriangleLB(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true)
  {
//--- If the drawing area is invalid, return 'false'
   if(!this.CheckBound(__FUNCTION__))
      return false;

//--- Coordinates of the shape
   int x1=x;
   int y1=y;
   int x2=x1+w;
   int y2=y1+h;
   int x3=x1;
   int y3=y2;
   
//--- Draw a triangle
   this.m_canvas.FillTriangle(x1,y1,x2,y2,x3,y3,::ColorToARGB(clr,alpha));

   if(update)
      this.m_canvas.Update(false);
   return true;
  }
//+------------------------------------------------------------------+
//| Draw a filled triangle in the upper-right corner                 |
//+------------------------------------------------------------------+
bool CImagePainter::TriangleRT(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true)
  {
//--- If the drawing area is invalid, return 'false'
   if(!this.CheckBound(__FUNCTION__))
      return false;

//--- Coordinates of the shape
   int x1=x;
   int y1=y;
   int x2=x1+w;
   int y2=y;
   int x3=x2;
   int y3=y2+h;
   
//--- Draw a triangle
   this.m_canvas.FillTriangle(x1,y1,x2,y2,x3,y3,::ColorToARGB(clr,alpha));

   if(update)
      this.m_canvas.Update(false);
   return true;
  }
//+------------------------------------------------------------------+
//| Draw a filled triangle in the lower-right corner                 |
//+------------------------------------------------------------------+
bool CImagePainter::TriangleRB(const int x,const int y,const int w,const int h,const color clr,const uchar alpha,const bool update=true)
  {
//--- If the drawing area is invalid, return 'false'
   if(!this.CheckBound(__FUNCTION__))
      return false;

//--- Coordinates of the shape
   int x1=x+w;
   int y1=y;
   int x2=x1;
   int y2=y+h;
   int x3=x;
   int y3=y2;
   
//--- Draw a triangle
   this.m_canvas.FillTriangle(x1,y1,x2,y2,x3,y3,::ColorToARGB(clr,alpha));

   if(update)
      this.m_canvas.Update(false);
   return true;
  }

A cada uno de los métodos se le pasan las coordenadas del rectángulo en cuyo interior hay que dibujar un triángulo relleno con el color indicado. Los métodos calculan todas las coordenadas del triángulo que se va a dibujar y llaman al método de la clase CCanvas que dibuja un triángulo relleno. Si se pasa al método la bandera de actualización del canvas activada, el canvas se actualiza.

A la clase del objeto del panel añadiremos un método que devuelva el número de áreas creadas en el objeto:

//+------------------------------------------------------------------+
//| Panel class                                                      |
//+------------------------------------------------------------------+
class CPanel : public CLabel
  {
private:
   CElementBase      m_temp_elm;                // Temporary object for finding elements
   CBound            m_temp_bound;              // Temporary object for finding areas
protected:
   CListElm          m_list_elm;                // List of attached elements
   CListElm          m_list_bounds;             // List of areas
//--- Adds a new element to the list
   bool              AddNewElement(CElementBase *element);

public:
//--- Return a pointer to the list of (1) attached elements or (2) areas
   CListElm         *GetListAttachedElements(void)             { return &this.m_list_elm;                         }
   CListElm         *GetListBounds(void)                       { return &this.m_list_bounds;                      }
   
//--- Return the attached element by (1) list index, (2) identifier, or (3) assigned object name
   CElementBase     *GetAttachedElementAt(const uint index)    { return this.m_list_elm.GetNodeAtIndex(index);    }
   CElementBase     *GetAttachedElementByID(const int id);
   CElementBase     *GetAttachedElementByName(const string name);
   
//--- Return the number of (1) areas, (2) attached elements,
   int               BoundsTotal(void)                   const { return this.m_list_bounds.Total();               }
   int               AttachedElementsTotal(void)         const { return this.m_list_elm.Total();                  }

//--- Return an area by (1) list index, (2) identifier, or (3) assigned area name
   CBound           *GetBoundAt(const uint index)              { return this.m_list_bounds.GetNodeAtIndex(index); }
   CBound           *GetBoundByID(const int id);
   CBound           *GetBoundByName(const string name);

No todas las áreas creadas tienen necesariamente un elemento gráfico asignado; por lo tanto, no es correcto utilizar el método que devuelve el número de elementos asociados para obtener el número de áreas. El nuevo método devuelve precisamente el número de áreas creadas en el elemento.

En el método que crea y añade un nuevo elemento a la lista, añadiremos la creación de nuevos controles:

//+------------------------------------------------------------------+
//| CPanel::Creates and adds a new element to the list               |
//+------------------------------------------------------------------+
CElementBase *CPanel::InsertNewElement(const ENUM_ELEMENT_TYPE type,const string text,const string user_name,const int dx,const int dy,const int w,const int h)
  {
//--- Create a name for a graphical object
   int elm_total=this.m_list_elm.Total();
   string obj_name=this.NameFG()+"_"+ElementShortName(type)+(string)elm_total;
//--- Calculate coordinates
   int x=this.X()+dx;
   int y=this.Y()+dy;
//--- Depending on the object type, create a new object
   CElementBase *element=NULL;
   switch(type)
     {
      case ELEMENT_TYPE_LABEL                      :  element = new CLabel(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);             break;   // Text label
      case ELEMENT_TYPE_BUTTON                     :  element = new CButton(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);            break;   // Simple button
      case ELEMENT_TYPE_BUTTON_TRIGGERED           :  element = new CButtonTriggered(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Two-state button
      case ELEMENT_TYPE_BUTTON_ARROW_UP            :  element = new CButtonArrowUp(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);     break;   // Up arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_DOWN          :  element = new CButtonArrowDown(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Down arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_LEFT          :  element = new CButtonArrowLeft(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Left arrow button
      case ELEMENT_TYPE_BUTTON_ARROW_RIGHT         :  element = new CButtonArrowRight(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);  break;   // Right arrow button
      case ELEMENT_TYPE_CHECKBOX                   :  element = new CCheckBox(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);          break;   // CheckBox control
      case ELEMENT_TYPE_RADIOBUTTON                :  element = new CRadioButton(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);       break;   // RadioButton control
      case ELEMENT_TYPE_SCROLLBAR_THUMB_H          :  element = new CScrollBarThumbH(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Thumb of the horizontal ScrollBar
      case ELEMENT_TYPE_SCROLLBAR_THUMB_V          :  element = new CScrollBarThumbV(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Thumb of the vertical ScrollBar
      case ELEMENT_TYPE_SCROLLBAR_H                :  element = new CScrollBarH(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);        break;   // Horizontal ScrollBar control
      case ELEMENT_TYPE_SCROLLBAR_V                :  element = new CScrollBarV(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);        break;   // Vertical ScrollBar control
      case ELEMENT_TYPE_TABLE_ROW_VIEW             :  element = new CTableRowView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);      break;   // Object for the visual representation of a table row
      case ELEMENT_TYPE_TABLE_CAPTION_VIEW         :  element = new CCaptionView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);       break;   // Base header object (View)
      case ELEMENT_TYPE_TABLE_COLUMN_CAPTION_VIEW  :  element = new CColumnCaptionView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h); break;   // Object for the visual representation of a table column header
      case ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW     :  element = new CRowCaptionView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);    break;   // Object for the visual representation of a table row header
      case ELEMENT_TYPE_TABLE_HEADER_VIEW          :  element = new CTableHeaderView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);   break;   // Object for the visual representation of a table header
      case ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW     :  element = new CTableRowsHeaderView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);break;  // Object for the visual representation of table row headers
      case ELEMENT_TYPE_TABLE_VIEW                 :  element = new CTableView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);         break;   // Object for the visual representation of a table
      case ELEMENT_TYPE_PANEL                      :  element = new CPanel(obj_name,"",this.m_chart_id,this.m_wnd,x,y,w,h);               break;   // Panel control
      case ELEMENT_TYPE_GROUPBOX                   :  element = new CGroupBox(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);          break;   // GroupBox control
      case ELEMENT_TYPE_CONTAINER                  :  element = new CContainer(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h);         break;   // Container control
      default                                      :  element = NULL;
     }

//--- If the new element has not been created, report this and return NULL
   if(element==NULL)
     {
      ::PrintFormat("%s: Error. Failed to create graphic element %s",__FUNCTION__,ElementDescription(type));
      return NULL;
     }
//--- Set the element's ID, name, container, and z-order
   element.SetID(elm_total);
   element.SetName(user_name);
   element.SetContainerObj(&this);
   element.ObjectSetZOrder(this.ObjectZOrder()+1);
   
//--- If the created element has not been added to the list, report this, delete the created element, and return NULL
   if(!this.AddNewElement(element))
     {
      ::PrintFormat("%s: Error. Failed to add %s element with ID %d to list",__FUNCTION__,ElementDescription(type),element.ID());
      delete element;
      return NULL;
     }
//--- Get the parent element to which the child elements are attached
   CElementBase *elm=this.GetContainer();
//--- If the parent element is of the "Container" type, then it has scrollbars
   if(elm!=NULL && elm.Type()==ELEMENT_TYPE_CONTAINER)
     {
      //--- Convert CElementBase to CContainer
      CContainer *container_obj=elm;
      //--- If the horizontal scrollbar is visible,
      if(container_obj.ScrollBarHorzIsVisible())
        {
         //--- Get a pointer to the horizontal scrollbar and bring it to the front
         CScrollBarH *sbh=container_obj.GetScrollBarH();
         if(sbh!=NULL)
            sbh.BringToTop(false);
        }
      //--- If the vertical scrollbar is visible,
      if(container_obj.ScrollBarVertIsVisible())
        {
         //--- Get a pointer to the vertical scrollbar and bring it to the front
         CScrollBarV *sbv=container_obj.GetScrollBarV();
         if(sbv!=NULL)
            sbv.BringToTop(false);
        }
     }
//--- Return a pointer to the created and attached element
   return element;
  }

Ahora será posible crear estos elementos a partir del objeto del panel y añadirlos a la lista de elementos asociados.

En la clase del objeto contenedor CContainer, optimizaremos el método que desplaza el contenido horizontalmente la distancia indicada:

//+-------------------------------------------------------------------+
//|CContainer::Shift the content horizontally by the specified value  |
//+-------------------------------------------------------------------+
bool CContainer::ContentShiftHorz(const int value)
  {
//--- Get a pointer to the container's content
   CElementBase *elm=this.GetAttachedElement();
   if(elm==NULL)
      return false;
   
//--- Calculate the offset amount based on the scrollbar slider position
   int content_offset=this.CalculateContentOffsetHorz(value);
   
//--- For the CTableView element, get the table header
   bool res=true;
   CElementBase     *elm_container=elm.GetContainer();
   CTableHeaderView *table_header=NULL;
   if(elm_container!=NULL && ::StringFind(elm.Name(),"Table")==0)
     {
      CElementBase *obj=elm_container.GetContainer();
      if(obj!=NULL && obj.Type()==ELEMENT_TYPE_TABLE_VIEW)
        {
         CTableView *table_view=obj;
         table_header=table_view.GetHeader();
         //--- Shift the header
         if(table_header!=NULL)
            res &=table_header.MoveX(this.X()-content_offset);
        }
     }

//--- Return the result of shifting the content by the calculated amount
   res &=elm.MoveX(this.X()-content_offset);
   return res;
  }

Aquí simplemente hemos eliminado una condición innecesaria. Los retoques son mínimos.

Ahora, en el método que desplaza el contenido verticalmente, también añadiremos el desplazamiento del encabezado vertical:

//+------------------------------------------------------------------+
//| CContainer::Shift the content vertically by the specified value  |
//+------------------------------------------------------------------+
bool CContainer::ContentShiftVert(const int value)
  {
//--- Get a pointer to the container's content
   CElementBase *elm=this.GetAttachedElement();
   if(elm==NULL)
      return false;
   
//--- Calculate the offset amount based on the scrollbar slider position
   int content_offset=this.CalculateContentOffsetVert(value);
   
//--- For a CTableView element, get the table's vertical header
   bool res=true;
   CElementBase         *elm_container=elm.GetContainer();
   CTableRowsHeaderView *table_header=NULL;
   if(elm_container!=NULL && ::StringFind(elm.Name(),"Table")==0)
     {
      CElementBase *obj=elm_container.GetContainer();
      if(obj!=NULL && obj.Type()==ELEMENT_TYPE_TABLE_VIEW)
        {
         CTableView *table_view=obj;
         table_header=table_view.GetRowsHeader();
         //--- Shift the header
         if(table_header!=NULL)
            res &=table_header.MoveY(this.Y()-content_offset);
        }
     }

//--- Return the result of shifting the content by the calculated amount
   res &=elm.MoveY(this.Y()-content_offset);
   return res;
  }

Después, la celda de la tabla debe poder tener su propia configuración del color de fondo en lugar de heredarlo de la fila en la que se encuentra.

En la clase del objeto celda, declararemos una variable para almacenar el color de fondo y métodos para establecer y obtener dicho color:

//+------------------------------------------------------------------+
//| Table cell visual representation class                           |
//+------------------------------------------------------------------+
class CTableCellView : public CBoundedObj
  {
protected:
   CTableCell       *m_table_cell_model;                       // Pointer to the cell model
   CImagePainter    *m_painter;                                // Pointer to the drawing object
   CTableRowView    *m_element_base;                           // Pointer to the base element (table row)
   CCanvas          *m_background;                             // Pointer to the background canvas
   CCanvas          *m_foreground;                             // Pointer to the foreground canvas
   int               m_index;                                  // Index in the cell list
   ENUM_ANCHOR_POINT m_text_anchor;                            // Text anchor point (alignment in the cell)
   int               m_text_x;                                 // X coordinate of the text (offset relative to the left edge of the object area)
   int               m_text_y;                                 // Y coordinate of the text (offset relative to the top edge of the object area)
   ushort            m_text[];                                 // Text
   color             m_fore_color;                             // Foreground color
   color             m_back_color;                             // Background color
   
//--- Return the offsets of the initial drawing coordinates on the drawing canvas relative to the canvas and the base element coordinates
   int               CanvasOffsetX(void)     const { return(this.m_element_base.ObjectX()-this.m_element_base.X());  }
   int               CanvasOffsetY(void)     const { return(this.m_element_base.ObjectY()-this.m_element_base.Y());  }
   
//--- Return the adjusted coordinate of a point on the canvas, taking into account the canvas offset relative to the base element
   int               AdjX(const int x)                            const { return(x-this.CanvasOffsetX());            }
   int               AdjY(const int y)                            const { return(y-this.CanvasOffsetY());            }

//--- Return the X and Y coordinates of the text based on the text anchor point
   bool              GetTextCoordsByAnchor(int &x, int &y, int &dir_x, int dir_y);

//--- Return a pointer to the table row panel container
   CContainer       *GetRowsPanelContainer(void);
   
public:
//--- Return a pointer to the assigned canvas: (1) background, (2) foreground
   CCanvas          *GetBackground(void)                                { return this.m_background;                  }
   CCanvas          *GetForeground(void)                                { return this.m_foreground;                  }

//--- Get the bounds of the parent container object
   int               ContainerLimitLeft(void)   const { return(this.m_element_base==NULL ? this.X()      :  this.m_element_base.LimitLeft());   }
   int               ContainerLimitRight(void)  const { return(this.m_element_base==NULL ? this.Right()  :  this.m_element_base.LimitRight());  }
   int               ContainerLimitTop(void)    const { return(this.m_element_base==NULL ? this.Y()      :  this.m_element_base.LimitTop());    }
   int               ContainerLimitBottom(void) const { return(this.m_element_base==NULL ? this.Bottom() :  this.m_element_base.LimitBottom()); }

//--- Return a flag indicating that the object is outside its container
   virtual bool      IsOutOfContainer(void);

//--- (1) Set, (2) return the cell text
   void              SetText(const string text)                         { ::StringToShortArray(text,this.m_text);    }
   string            Text(void)                                   const { return ::ShortArrayToString(this.m_text);  }

//--- (1) Set, (2) return the cell text color
   void              SetForeColor(const color clr)                      { this.m_fore_color=clr;                     }
   color             ForeColor(void)                              const { return this.m_fore_color;                  }

//--- (1) Set, (2) return the cell background color
   void              SetBackColor(const color clr)                      { this.m_back_color=clr;                     }
   color             BackColor(void)                              const { return this.m_back_color;                  }

//--- Set the identifier
   virtual void      SetID(const int id)                                { this.m_id=id;                              }
//--- (1) Set, (2) return the cell index
   void              SetIndex(const int index)                          { this.m_index=index;                        }
   int               Index(void)                                  const { return this.m_index;                       }

//--- (1) Set, (2) return the text offset along the X-axis
   void              SetTextShiftX(const int shift)                     { this.m_text_x=shift;                       }
   int               TextShiftX(void)                             const { return this.m_text_x;                      }
   
//--- (1) Set, (2) return the text offset along the Y-axis
   void              SetTextShiftY(const int shift)                     { this.m_text_y=shift;                       }
   int               TextShiftY(void)                             const { return this.m_text_y;                      }
   
//--- (1) Set, (2) return the text anchor point
   void              SetTextAnchor(const ENUM_ANCHOR_POINT anchor,const bool cell_redraw,const bool chart_redraw);
   int               TextAnchor(void)                             const { return this.m_text_anchor;                 }
   
//--- Set the text anchor point and text offsets
   void              SetTextPosition(const ENUM_ANCHOR_POINT anchor,const int shift_x,const int shift_y,const bool cell_redraw,const bool chart_redraw);

//--- Assign the base element (table row)
   void              RowAssign(CTableRowView *base_element);
   
//--- (1) Assign, (2) return the cell model
   bool              TableCellModelAssign(CTableCell *cell_model,int dx,int dy,int w,int h);
   CTableCell       *GetTableCellModel(void)                            { return this.m_table_cell_model;            }

//--- Print the assigned cell model to the log
   void              TableCellModelPrint(void);
   
//--- (1) Fill the object with the background color, (2) update the object to display the changes, (3) draw the appearance
   virtual void      Clear(const bool chart_redraw);
   virtual void      Update(const bool chart_redraw);
   virtual void      Draw(const bool chart_redraw);
   
//--- Display text
   virtual void      DrawText(const int dx, const int dy, const string text, const bool chart_redraw);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CBaseObj::Compare(node,mode);       }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_CELL_VIEW);      }
   
//--- Initialize a class object
   void              Init(const string text);
   
//--- Return a description of the object
   virtual string    Description(void);
   
//--- Constructors/destructor
                     CTableCellView(void);
                     CTableCellView(const int id, const string user_name, const string text, const int x, const int y, const int w, const int h);
                    ~CTableCellView (void){}
  };

En el método que asigna a la celda una fila y los canvas de fondo y de primer plano, inicializaremos el color de fondo de la celda con el color de fondo de la fila en la que se encuentra la celda:

//+--------------------------------------------------------------------------+
//| CTableCellView::Assign a row and the background and foreground canvases  |
//+--------------------------------------------------------------------------+
void CTableCellView::RowAssign(CTableRowView *base_element)
  {
   if(base_element==NULL)
     {
      ::PrintFormat("%s: Error. Empty element passed",__FUNCTION__);
      return;
     }
   this.m_element_base=base_element;
   this.m_background=this.m_element_base.GetBackground();
   this.m_foreground=this.m_element_base.GetForeground();
   this.m_painter=this.m_element_base.Painter();
   this.m_fore_color=this.m_element_base.ForeColor();
   this.m_back_color=this.m_element_base.BackColor();
  }

Por defecto, el color de fondo de la celda será el mismo que el de la fila.

En el método que dibuja la celda, añadiremos el dibujo del fondo de la celda:

//+------------------------------------------------------------------+
//| CTableCellView::Draw the appearance                              |
//+------------------------------------------------------------------+
void CTableCellView::Draw(const bool chart_redraw)
  {
//--- If the cell is outside the table row container, exit
   if(this.IsOutOfContainer())
      return;
      
//--- Get the text coordinates and the offset direction based on the text anchor point
   int text_x=0, text_y=0;
   int dir_horz=0, dir_vert=0;
   if(!this.GetTextCoordsByAnchor(text_x,text_y,dir_horz,dir_vert))
      return;
//--- Adjust the text coordinates
   int x=this.AdjX(this.X()+text_x);
   int y=this.AdjY(this.Y()+text_y);
   
//--- Set the coordinates of the separator line
   int x1=this.AdjX(this.X());
   int y1=this.AdjY(this.Y());
   int x2=this.AdjX(this.X());
   int y2=this.AdjY(this.Bottom());

//--- Draw the text on the foreground canvas, taking the offset direction into account, without updating the chart
   this.DrawText(x+this.m_text_x*dir_horz,y+this.m_text_y*dir_vert,this.Text(),false);
   
//--- Set the coordinates for a rectangular fill
   x1=this.AdjX(this.X());
   y1=this.AdjY(this.Y());
   x2=this.AdjX(this.Right());
   y2=this.AdjY(this.Bottom()-1);
   this.m_background.FillRectangle(x1,y1,x2,y2,::ColorToARGB(this.BackColor(),this.m_element_base.AlphaBG()));

//--- If this is not the rightmost cell, draw a vertical divider to the right of the cell
   if(this.m_element_base!=NULL && this.Index()<this.m_element_base.CellsTotal()-1)
     {
      int line_x=this.AdjX(this.Right());
      this.m_background.Line(line_x,y1,line_x,y2,::ColorToARGB(this.m_element_base.BorderColor(),this.m_element_base.AlphaBG()));
     }
//--- Update the background canvas with the specified chart redraw flag
   this.m_background.Update(chart_redraw);
  }

El bloque de código resaltado en color dibuja incondicionalmente un rectángulo relleno que ocupa toda la celda. Más adelante añadiremos aquí una comprobación del modo de resaltado de la fila y, si toda la fila se resalta al paso del cursor, este bloque de código no deberá ejecutarse. Por ahora, para simplificar, nos limitaremos a rellenar por completo el fondo de la celda con el color establecido.

Ahora modificaremos la clase de la vista de una fila de tabla, CTableRowView.

Y luego declararemos las nuevas variables, métodos y manejadores de eventos:

//+------------------------------------------------------------------+
//| Table row visual representation class                            |
//+------------------------------------------------------------------+
class CTableRowView : public CPanel
  {
protected:
   CTableCellView    m_temp_cell;                                    // Temporary cell object for searching
   CTableRow        *m_table_row_model;                              // Pointer to the row model
   CListElm          m_list_cells;                                   // List of cells
   int               m_index;                                        // Index in the list of rows
   ENUM_ROWS_HIGHLIGHT_MODE m_highlight_mode;                        // Row highlighting mode
   
//--- Create and add a new cell view object to the list
   CTableCellView   *InsertNewCellView(const int index,const string text,const int dx,const int dy,const int w,const int h);
//--- Delete the specified row area and the cell with the corresponding index
   bool              BoundCellDelete(const int index);
//--- Return the visual representation of (1) the table, (2) the column header, and (3) the row header
   CTableView       *GetTableView(void);
   CTableHeaderView *GetHeaderView(void);
   CTableRowsHeaderView *GetRowsHeaderView(void);
   
//--- Set the specified (1) column header or (2) row header as selected
   void              SetColumnCaptionSelected(const uint index);
   void              SetRowCaptionSelected(const uint index);
//--- Clear selection from all (1) column headers and (2) row headers
   void              SetAllColumnCaptionsUnselected(const int exclude=-1);
   void              SetAllRowCaptionsUnselected(const int exclude=-1);
   
public:
//--- Return (1) the list, (2) the number of cells, (3) a cell, (4) the column header, and (5) the row header
   CListElm         *GetListCells(void)                                 { return &this.m_list_cells;                       }
   int               CellsTotal(void)                             const { return this.m_list_cells.Total();                }
   CTableCellView   *GetCellView(const uint index)                      { return this.m_list_cells.GetNodeAtIndex(index);  }
   CColumnCaptionView *GetColumnCaption(const uint index);
   CRowCaptionView  *GetRowCaption(const uint index);
   
//--- Set the identifier
   virtual void      SetID(const int id)                                { this.m_id=id;                                    }
//--- (1) Set, (2) return the row index
   void              SetIndex(const int index)                          { this.m_index=index;                              }
   int               Index(void)                                  const { return this.m_index;                             }

//--- (1) Set, (2) return the row model
   bool              TableRowModelAssign(CTableRow *row_model);
   CTableRow        *GetTableRowModel(void)                             { return this.m_table_row_model;                   }
//--- Update the row with the updated model
   bool              TableRowModelUpdate(CTableRow *row_model);

//--- (1) Set, (2) return the row highlighting mode
   void              SetHighlightMode(const ENUM_ROWS_HIGHLIGHT_MODE mode) { this.m_highlight_mode=mode;                   }
   ENUM_ROWS_HIGHLIGHT_MODE HighlightMode(void)                   const { return this.m_highlight_mode;                    }
   
//--- Recalculate cell areas
   bool              RecalculateBounds(CListElm *list_bounds);

//--- Print the assigned row model to the log
   void              TableRowModelPrint(const bool detail, const bool as_table=false, const int cell_width=CELL_WIDTH_IN_CHARS);
   
//--- Draw the appearance
   virtual void      Draw(const bool chart_redraw);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CLabel::Compare(node,mode);               }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_ROW_VIEW);             }
  
//--- Initialization of (1) a class object and (2) the object's default colors
   void              Init(void);
   virtual void      InitColors(void);

//--- Event handlers for (1) cursor hover (Focus), (2) mouse button presses (Press),
   virtual void      OnFocusEvent(const int id, const long lparam, const double dparam, const string sparam);
   virtual void      OnPressEvent(const int id, const long lparam, const double dparam, const string sparam);
   
//--- Constructors/destructor
                     CTableRowView(void);
                     CTableRowView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h);
                    ~CTableRowView (void){ this.m_list_cells.Clear(); }
  };

En los constructores de la clase, inicializamos el modo de resaltado por defecto como "toda la fila":

//+------------------------------------------------------------------------+
//| CTableRowView::Default constructor. Creates the object in the main     |
//| window of the current chart at coordinates 0,0 with default dimensions |
//+------------------------------------------------------------------------+
CTableRowView::CTableRowView(void) : CPanel("TableRow","",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H), m_index(-1), m_highlight_mode(ROWS_HIGHLIGHT_MODE_ROW)
  {
//--- Initialization
   this.Init();
  }
//+----------------------------------------------------------------------+
//| CTableRowView::Parameterized constructor. Creates the object in      |
//| the specified window of the specified chart with the specified text, |
//| coordinates, and dimensions                                          |
//+----------------------------------------------------------------------+
CTableRowView::CTableRowView(const string object_name,const string text,const long chart_id,const int wnd,const int x,const int y,const int w,const int h) :
   CPanel(object_name,text,chart_id,wnd,x,y,w,h), m_index(-1), m_highlight_mode(ROWS_HIGHLIGHT_MODE_ROW)
  {
//--- Initialization
   this.Init();
  }

Vamos a escribir la implementación de los nuevos métodos.

Método que devuelve la vista de la tabla:

//+------------------------------------------------------------------+
//| CTableRowView::Return the table's visual representation          |
//+------------------------------------------------------------------+
CTableView *CTableRowView::GetTableView(void)
  {
   CTableView *obj=NULL;
//--- Get the table row panel
   CElementBase *base0=this.GetContainer();
   if(base0==NULL)
      return NULL;
   
//--- Get the table row panel container
   CElementBase *base1=base0.GetContainer();
   if(base1==NULL)
      return NULL;
   
//--- Get the table visual representation object
   CElementBase *base2=base1.GetContainer();
   if(base2!=NULL && base2.Type()==ELEMENT_TYPE_TABLE_VIEW)
     {
      obj=base2;
      return obj;
     }
   return NULL;
  }

La tabla está estructurada de la siguiente manera:

En el panel de tipo "Tabla" (1) se encuentran el encabezado de la tabla y un contenedor (2), en cuyo interior hay un panel desplazable (3), en el que, a su vez, se sitúan las filas de la tabla (4), representadas por la clase que estamos analizando.
Para obtener el objeto de la tabla (1), es necesario obtener el objeto panel padre (3), al que está asociada la fila. A continuación, a partir del panel (3) obtenemos su objeto contenedor padre (2) y a partir del contenedor, su objeto tabla padre (1).

Método que devuelve la vista del encabezado horizontal:

//+------------------------------------------------------------------+
//| CTableRowView::Returns a visual representation of the            |
//| column headers                                                   |
//+------------------------------------------------------------------+
CTableHeaderView *CTableRowView::GetHeaderView(void)
  {
   CTableView *table=this.GetTableView();
   return(table!=NULL ? table.GetHeader() : NULL);
  }

Aquí obtenemos el objeto "tabla" mediante el método descrito anteriormente y, a partir de él, el objeto "encabezado horizontal".

Método que devuelve la vista del encabezado vertical:

//+------------------------------------------------------------------+
//|CTableRowView::Return a visual representation of the row header   |
//+------------------------------------------------------------------+
CTableRowsHeaderView *CTableRowView::GetRowsHeaderView(void)
  {
   CTableView *table=this.GetTableView();
   return(table!=NULL ? table.GetRowsHeader() : NULL);
  }

Ahora obtenemos el objeto "tabla" y, a partir de él, el objeto "encabezado vertical", cuya implementación analizaremos más adelante.

Método que devuelve el encabezado de una columna:

//+------------------------------------------------------------------+
//| CTableRowView::Return the column header                          |
//+------------------------------------------------------------------+
CColumnCaptionView *CTableRowView::GetColumnCaption(const uint index)
  {
   CTableHeaderView *header=this.GetHeaderView();
   return(header!=NULL ? header.GetColumnCaption(index) : NULL);
  }

Aquí primero obtenemos el objeto del encabezado horizontal mediante el método descrito anteriormente y, a partir de él, el encabezado de columna indicado por el índice.

Método que devuelve el encabezado de una fila:

//+------------------------------------------------------------------+
//| CTableRowView::Return a row header                               |
//+------------------------------------------------------------------+
CRowCaptionView *CTableRowView::GetRowCaption(const uint index)
  {
   CTableRowsHeaderView *header=this.GetRowsHeaderView();
   return(header!=NULL ? header.GetRowCaption(index) : NULL);
  }

Mediante el método descrito anteriormente, obtenemos el objeto del encabezado vertical, cuya implementación analizaremos más adelante, y, a partir de él, el encabezado de fila indicado por el índice.

Método que marca como seleccionado el encabezado de columna especificado:

//+------------------------------------------------------------------+
//|CTableRowView::Set the specified column header as selected        |
//+------------------------------------------------------------------+
void CTableRowView::SetColumnCaptionSelected(const uint index)
  {
   CColumnCaptionView *capt=this.GetColumnCaption(index);
   if(capt==NULL || capt.State()==ELEMENT_STATE_ACT)
      return;
   capt.SetState(ELEMENT_STATE_ACT);
   capt.GetBackground().FillRectangle(0,capt.Height()-2,capt.Width()-1,capt.Height()-1,ColorToARGB(clrCadetBlue));
   capt.GetBackground().Update(false);
  }

El encabezado de una columna puede tener el estado de seleccionado. Por ejemplo, para marcar como seleccionado el encabezado correspondiente a la celda seleccionada de la tabla. El método comprueba que el encabezado de tabla obtenido no esté ya seleccionado, establece la bandera de objeto seleccionado y dibuja una fina línea de selección debajo del encabezado.

Método que marca como seleccionado el encabezado de fila especificado:

//+------------------------------------------------------------------+
//| CTableRowView::Set the specified row header as selected          |
//+------------------------------------------------------------------+
void CTableRowView::SetRowCaptionSelected(const uint index)
  {
   CRowCaptionView *capt=this.GetRowCaption(index);
   if(capt==NULL || capt.State()==ELEMENT_STATE_ACT)
      return;
   capt.SetState(ELEMENT_STATE_ACT);
   capt.GetBackground().FillRectangle(capt.Width()-2,2,capt.Width()-1,capt.Height()-0,ColorToARGB(clrCadetBlue));
   capt.GetBackground().Update(false);
  }

La lógica de este método es similar a la del anterior, con la única diferencia de que se selecciona el borde derecho del encabezado.

Método para eliminar la selección de todos los encabezados de columna:

//+------------------------------------------------------------------+
//| CTableRowView::Deselect all column headers                       |
//+------------------------------------------------------------------+
void CTableRowView::SetAllColumnCaptionsUnselected(const int exclude=-1)
  {
   CTableHeaderView *header=this.GetHeaderView();
   if(header==NULL)
      return;
   int total=header.BoundsTotal();
   for(int i=0;i<total;i++)
     {
      CColumnCaptionView *capt=this.GetColumnCaption(i);
      if(capt==NULL || (exclude>-1 && i==exclude))
         continue;
      if(capt.State()!=ELEMENT_STATE_DEF)
        {
         capt.SetState(ELEMENT_STATE_DEF);
         capt.Draw(false);
        }
     }
  }

Al método se le pasa el índice del encabezado que debe permanecer seleccionado. Luego se elimina la selección de todos los demás. En un bucle que recorre todos los encabezados, obtenemos cada encabezado de columna y comprobamos si es el que se ha indicado como excepción. Si el índice del bucle coincide con el indicado en exclude, ese encabezado permanece seleccionado. Después se elimina la selección de todos los demás encabezados. Si se pasa un valor negativo a exclude, se elimina el estado de selección de todos los encabezados.

Método para eliminar la selección de todos los encabezados de fila:

//+------------------------------------------------------------------+
//| CTableRowView::Deselect all row headers                          |
//+------------------------------------------------------------------+
void CTableRowView::SetAllRowCaptionsUnselected(const int exclude=-1)
  {
   CTableRowsHeaderView *header=this.GetRowsHeaderView();
   if(header==NULL)
      return;
   int total=header.BoundsTotal();
   for(int i=0;i<total;i++)
     {
      CRowCaptionView *capt=this.GetRowCaption(i);
      if(capt==NULL || (exclude>-1 && capt.ID()==exclude))
         continue;
      if(capt.State()!=ELEMENT_STATE_DEF)
        {
         capt.SetState(ELEMENT_STATE_DEF);
         capt.Draw(false);
        }
     }
  }

La lógica de este método es idéntica a la del método analizado anteriormente.

Manejador del paso del cursor:

//+------------------------------------------------------------------+
//| CTableRowView::Cursor hover handler                              |
//+------------------------------------------------------------------+
void CTableRowView::OnFocusEvent(const int id,const long lparam,const double dparam,const string sparam)
  {
//--- If the entire row is being processed, call the event handler of the parent class
   if(this.m_highlight_mode==ROWS_HIGHLIGHT_MODE_ROW)
     {
      CCanvasBase::OnFocusEvent(id,lparam,dparam,sparam);
      return;
     }

//--- Get the cursor coordinates
   int x=int(lparam-this.X());
   int y=int(dparam-this.m_wnd_y-this.Y());

//--- Loop through the row's cell areas
   int total=this.m_list_bounds.Total();
   for(int i=0;i<total;i++)
     {
      //--- get the next area
      CBound *bound=this.GetBoundAt(i);
      if(bound==NULL)
         continue;

      //--- Get the element assigned to the current area
      CBaseObj *obj=bound.GetAssignedObj();
      CTableCellView *cell=NULL;
      
      //--- If the retrieved element is not a table cell, continue
      if(obj==NULL || obj.Type()!=ELEMENT_TYPE_TABLE_CELL_VIEW)
         continue;

      //--- This is a table cell. Determine its coordinates in the table (row/column)
      cell=obj;
      int row=this.ID();
      int col=obj.ID();
      
      //--- Get the corresponding row and column headers
      CColumnCaptionView *col_capt=this.GetColumnCaption(col);
      CRowCaptionView    *row_capt=this.GetRowCaption(row);
      if(col_capt==NULL || row_capt==NULL)
         continue;
      
      //--- If the cursor is over the cell area
      if(bound.Contains(x,y))
        {
         //--- Set the column and row headers as selected,
         this.SetColumnCaptionSelected(i);
         this.SetRowCaptionSelected(this.ID());
         //--- Clear the “selected header” flag from all row headers except the current one
         this.SetAllRowCaptionsUnselected(this.ID());
        }
      //--- If the cursor is outside the cell area
      else
        {
         //--- If the header is selected,
         if(col_capt.State()!=ELEMENT_STATE_DEF)
           {
            //--- clear its selection and redraw the object as unselected
            col_capt.SetState(ELEMENT_STATE_DEF);
            col_capt.Draw(false);
           }
        }
     }
  }

La lógica del manejador se explica en sus comentarios. Si se resalta toda la fila, se invoca el manejador "objeto en foco" de la clase padre. De lo contrario, se busca la celda en la tabla según sus coordenadas y, si el cursor se sitúa sobre ella, se seleccionan los encabezados de fila y columna correspondientes a dicha celda. No se han implementado aquí otros cambios en el aspecto de la celda; esta tarea queda pendiente para futuras mejoras.

Manejador de pulsación sobre un objeto:

//+------------------------------------------------------------------+
//| CTableRowView::Object click handler                              |
//+------------------------------------------------------------------+
void CTableRowView::OnPressEvent(const int id,const long lparam,const double dparam,const string sparam)
  {
//--- If the entire row is being processed, call the parent class event handler
   if(this.m_highlight_mode==ROWS_HIGHLIGHT_MODE_ROW)
     {
      CCanvasBase::OnPressEvent(id,lparam,dparam,sparam);
      return;
     }

//--- In a loop through all row areas
   int total=this.m_list_bounds.Total();
   for(int i=0;i<total;i++)
     {
      //--- Get the next area
      CBound *bound=this.GetBoundAt(i);
      if(bound==NULL)
         continue;

      //--- Get the cursor coordinates and
      int x=int(lparam-this.X());
      int y=int(dparam-this.m_wnd_y-this.Y());
      //--- Check that the cursor is inside the area
      if(bound.Contains(x,y))
        {
         //--- Get the attached object (cell) from the area
         CBaseObj *obj=bound.GetAssignedObj();
         if(obj!=NULL)
           {
            //--- Write the cell address in the table (row/column)
            int row=this.ID();
            int col=obj.ID();
            
            //--- Based on the row and column identifiers, get pointers to the corresponding headers
            CRowCaptionView    *row_capt=this.GetRowCaption(row);
            CColumnCaptionView *col_capt=this.GetColumnCaption(col);
            if(row_capt==NULL || col_capt==NULL)
               return;
            
            //--- Create a text value for the custom event from the row name and header texts
            string sprm=obj.Name()+";"+row_capt.Text()+";"+col_capt.Text();
            //--- Send a custom object-click event with the row and column coordinates and text
            ::EventChartCustom(this.m_chart_id,CHARTEVENT_OBJECT_CLICK,row,col,sprm);
           }
        }
     }
  }

La lógica del método se explica en sus comentarios. Si se procesa toda la fila, se invoca el manejador "objeto en foco" de la clase padre. De lo contrario, se busca la celda en la tabla según sus coordenadas y, si el cursor se sitúa sobre ella, se crea una cadena con los textos de los encabezados de fila y columna (nombres de símbolos en el contexto de este artículo), separados por ";". A continuación, se envía un evento personalizado de clic sobre el objeto con los índices de fila en lparam y de columna en dparam, y con la cadena creada a partir de los textos de los encabezados en sparam. Luego se puede recibir este evento en el programa y determinar en qué celda se ha producido el clic para procesar dicho evento.

En los métodos de gestión de archivos, guardamos y cargamos el valor del modo de resaltado:

//+------------------------------------------------------------------+
//| CTableRowView::Save to a file                                    |
//+------------------------------------------------------------------+
bool CTableRowView::Save(const int file_handle)
  {
//--- Save the parent object's data
   if(!CPanel::Save(file_handle))
      return false;

//--- Save the list of cells
   if(!this.m_list_cells.Save(file_handle))
      return false;
//--- Save the row number
   if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE)
      return false;
//--- Save the highlighting mode
   if(::FileWriteInteger(file_handle,this.m_highlight_mode,INT_VALUE)!=INT_VALUE)
      return false;
   
//--- Completed successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CTableRowView::Load from a file                                  |
//+------------------------------------------------------------------+
bool CTableRowView::Load(const int file_handle)
  {
//--- Load data from the parent object
   if(!CPanel::Load(file_handle))
      return false;
     
//--- Load the list of cells
   if(!this.m_list_cells.Load(file_handle))
      return false;
//--- Load the row number
   this.m_index=(int)::FileReadInteger(file_handle,INT_VALUE);
//--- Load the highlighting mode
   this.m_highlight_mode=(ENUM_ROWS_HIGHLIGHT_MODE)::FileReadInteger(file_handle,INT_VALUE);
   
//--- Completed successfully
   return true;
  }

Como ahora habrá dos tipos de encabezados —el encabezado de columna y el encabezado de fila de la tabla—, la clase de encabezado de columna de la tabla creada y utilizada anteriormente debe dividirse en dos clases: una clase de encabezado abstracto y las clases de encabezado de columna y de fila de la tabla que heredan de ella. Las propiedades y la funcionalidad comunes de cualquier encabezado se transladan a la clase abstracta, mientras que en las clases derivadas se concretará la funcionalidad según el tipo de encabezado.

Clase abstracta de la vista del encabezado:

//+------------------------------------------------------------------+
//| Abstract class for the visual representation of a header         |
//+------------------------------------------------------------------+
class CCaptionView : public CButton
  {
protected:
   CBound           *m_bound_node;                                   // Pointer to the header area
   int               m_index;                                        // Index in the list of rows
   
public:
//--- Set the identifier
   virtual void      SetID(const int id)                                { this.m_id=id;                              }
//--- (1) Set, (2) return the row index
   void              SetIndex(const int index)                          { this.m_index=index;                        }
   int               Index(void)                                  const { return this.m_index;                       }

//--- (1) Assign, (2) return the header area to which the object is assigned
   void              AssignBoundNode(CBound *bound)                     { this.m_bound_node=bound;                   }
   CBound           *GetBoundNode(void)                                 { return this.m_bound_node;                  }

//--- Draw (1) the appearance and (2) the sort direction arrow
   virtual void      Draw(const bool chart_redraw);

//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CButton::Compare(node,mode);        }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_CAPTION_VIEW);   }
  
//--- Initialization of (1) a class object and (2) the object's default colors
   void              Init(const string text);
   virtual void      InitColors(void);
   
//--- Return a description of the object
   virtual string    Description(void);
   
//--- Constructors/destructor
                     CCaptionView(void);
                     CCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h); 
                    ~CCaptionView (void){}
  };
//+------------------------------------------------------------------+
//| CCaptionView::Default constructor. Constructs an object          |
//| in the main chart window of the current chart at coordinates 0,0 |
//| with default dimensions                                          |
//+------------------------------------------------------------------+
CCaptionView::CCaptionView(void) : CButton("Caption","Caption",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H), m_index(0)
  {
//--- Initialization
   this.Init("Caption");
   this.SetID(0);
   this.SetIndex(-1);
   this.SetName("Caption");
  }
//+----------------------------------------------------------------------------------+
//| CCaptionView::Parameterized constructor.                                         |
//| Construct the object in the specified chart window of the specified chart with   |
//| the specified text, coordinates, and dimensions                                  |
//+----------------------------------------------------------------------------------+
CCaptionView::CCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h) :
   CButton(object_name,text,chart_id,wnd,x,y,w,h), m_index(0)
  {
//--- Initialization
   this.Init(text);
   this.SetID(0);
   this.SetIndex(-1);
  }
//+------------------------------------------------------------------+
//| CCaptionView::Initialization                                     |
//+------------------------------------------------------------------+
void CCaptionView::Init(const string text)
  {
//--- Default text offsets
   this.m_text_x=4;
   this.m_text_y=2;
//--- Set colors for different states
   this.InitColors();
//--- Can be resized
   this.SetResizable(false);
   this.SetMovable(false);
   this.SetImageBound(this.ObjectWidth()-14,4,8,11);
  }
//+------------------------------------------------------------------+
//| CCaptionView::Default object color initialization                |
//+------------------------------------------------------------------+
void CCaptionView::InitColors(void)
  {
//--- Initialize the background colors for the normal and activated states and set the normal-state color as the current background color
   this.InitBackColors(C'230,230,230',C'159,213,183',this.GetBackColorControl().NewColor(C'159,213,183',-6,-6,-6),clrSilver);
   this.InitBackColorsAct(C'230,230,230',C'159,213,183',this.GetBackColorControl().NewColor(C'159,213,183',-6,-6,-6),clrSilver);
   this.BackColorToDefault();
   
//--- Initialize the foreground colors for the normal and activated states and set the normal-state color as the current text color
   this.InitForeColors(clrBlack,clrBlack,clrBlack,clrSilver);
   this.InitForeColorsAct(clrBlack,clrBlack,clrBlack,clrSilver);
   this.ForeColorToDefault();
   
//--- Initialize the border colors for the normal and activated states and set the normal-state color as the current border color
   this.InitBorderColors(clrLightGray,clrLightGray,clrLightGray,clrLightGray);
   this.InitBorderColorsAct(clrLightGray,clrLightGray,clrLightGray,clrLightGray);
   this.BorderColorToDefault();
   
//--- Initialize the border color and foreground color for the disabled element
   this.InitBorderColorBlocked(clrNULL);
   this.InitForeColorBlocked(clrSilver);
  }
//+------------------------------------------------------------------+
//| CCaptionView::Draw the appearance                                |
//+------------------------------------------------------------------+
void CCaptionView::Draw(const bool chart_redraw)
  {
//--- If the object is outside its container, return
   if(this.IsOutOfContainer())
      return;

//--- Fill the object with the background color, draw a light vertical line on the left and a dark one on the right
   this.Fill(this.BackColor(),false);
   color clr_dark =this.BorderColor();                                                       // "Dark color"
   color clr_light=this.GetBackColorControl().NewColor(this.BorderColor(), 100, 100, 100);   // "Light color"
   this.m_background.Line(this.AdjX(0),this.AdjY(0),this.AdjX(0),this.AdjY(this.Height()-1),::ColorToARGB(clr_light,this.AlphaBG()));                          // Line on the left
   this.m_background.Line(this.AdjX(this.Width()-1),this.AdjY(0),this.AdjX(this.Width()-1),this.AdjY(this.Height()-1),::ColorToARGB(clr_dark,this.AlphaBG())); // Line on the right
//--- Update the background canvas
   this.m_background.Update(false);
   
//--- Display the header text
   CLabel::Draw(false);
      
//--- If specified, update the chart
   if(chart_redraw)
      ::ChartRedraw(this.m_chart_id);
  }
//+------------------------------------------------------------------+
//| CCaptionView::Return the object description                      |
//+------------------------------------------------------------------+
string CCaptionView::Description(void)
  {
   string nm=this.Name();
   string name=(nm!="" ? ::StringFormat(" \"%s\"",nm) : nm);
   return ::StringFormat("%s%s ID %d, X %d, Y %d, W %d, H %d",ElementDescription((ENUM_ELEMENT_TYPE)this.Type()),name,this.ID(),this.X(),this.Y(),this.Width(),this.Height());
  }
//+------------------------------------------------------------------+
//| CCaptionView::Save to file                                       |
//+------------------------------------------------------------------+
bool CCaptionView::Save(const int file_handle)
  {
//--- Save the parent object data
   if(!CButton::Save(file_handle))
      return false;
  
//--- Save the header number
   if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE)
      return false;
      
//--- Success
   return true;
  }
//+------------------------------------------------------------------+
//| CCaptionView::Load from file                                     |
//+------------------------------------------------------------------+
bool CCaptionView::Load(const int file_handle)
  {
//--- Load the parent object data
   if(!CButton::Load(file_handle))
      return false;
      
//--- Load the header number
   this.m_index=::FileReadInteger(file_handle,INT_VALUE);
   
//--- Success
   return true;
  }

A esta clase se han trasladado todas las propiedades y métodos que se utilizan exactamente de la misma manera en cualquiera de las clases de encabezados derivadas de ella.

Ahora, la clase de encabezado de columna de la tabla creada anteriormente hereda de la clase abstracta de encabezado y tiene una estructura más reducida, ya que muchos métodos se han trasladado a la clase base abstracta de encabezado.

Analicemos la clase en su conjunto:

//+------------------------------------------------------------------+
//| Class for the visual representation of a table column header     |
//+------------------------------------------------------------------+
class CColumnCaptionView : public CCaptionView
  {
protected:
   CColumnCaption   *m_column_caption_model;                         // Pointer to the column header model
   ENUM_TABLE_SORT_MODE m_sort_mode;                                 // Table column sorting mode
   bool              m_sortable;                                     // Sort control flag
   
//--- Add tooltip objects with arrows to the list
   virtual bool      AddHintsArrowed(void);
//--- Display the resize cursor
   virtual bool      ShowCursorHint(const ENUM_CURSOR_REGION edge,int x,int y);
   
public:
//--- (1) Set, (2) return the column header model
   bool              ColumnCaptionModelAssign(CColumnCaption *caption_model);
   CColumnCaption   *ColumnCaptionModel(void)                           { return this.m_column_caption_model;        }

//--- Print the assigned column header model to the log
   void              ColumnCaptionModelPrint(void);

//--- (1) Set, (2) return the sortability flag
   void              SetSortableFlag(const bool flag)
                       {
                        this.m_sortable=flag;
                        this.SetSortMode(flag ? TABLE_SORT_MODE_ASC : TABLE_SORT_MODE_NONE);
                       }
   bool              IsSortabe(void)                              const { return this.m_sortable;                    }

//--- (1) Set, (2) return the sorting mode
   void              SetSortMode(const ENUM_TABLE_SORT_MODE mode)       { this.m_sort_mode=mode;                     }
   ENUM_TABLE_SORT_MODE SortMode(void)                            const { return this.m_sort_mode;                   }
   
//--- Set the opposite sort direction
   void              SetSortModeReverse(void);
   
//--- Draw (1) the appearance and (2) the sort direction arrow
   virtual void      Draw(const bool chart_redraw);
protected:
   void              DrawSortModeArrow(void);
public:  
//--- Handler for resizing the element from the right edge
   virtual bool      ResizeZoneRightHandler(const int x, const int y);
   
//--- Handlers for resizing an element from its sides and corners
   virtual bool      ResizeZoneLeftHandler(const int x, const int y)       { return false;                           }
   virtual bool      ResizeZoneTopHandler(const int x, const int y)        { return false;                           }
   virtual bool      ResizeZoneBottomHandler(const int x, const int y)     { return false;                           }
   virtual bool      ResizeZoneLeftTopHandler(const int x, const int y)    { return false;                           }
   virtual bool      ResizeZoneRightTopHandler(const int x, const int y)   { return false;                           }
   virtual bool      ResizeZoneLeftBottomHandler(const int x, const int y) { return false;                           }
   virtual bool      ResizeZoneRightBottomHandler(const int x, const int y){ return false;                           }
   
//--- Change the object's width
   virtual bool      ResizeW(const int w);
   
//--- Mouse button press event handler (Press)
   virtual void      OnPressEvent(const int id, const long lparam, const double dparam, const string sparam);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CButton::Compare(node,mode);        }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_COLUMN_CAPTION_VIEW);}
  
//--- Initialization of (1) a class object and (2) the object's default colors
   void              Init(const string text);
   //virtual void      InitColors(void);
   
//--- Return a description of the object
   virtual string    Description(void);
   
//--- Constructors/destructor
                     CColumnCaptionView(void);
                     CColumnCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h); 
                    ~CColumnCaptionView (void){}
  };
//+-------------------------------------------------------------------+
//| CColumnCaptionView::Default constructor. Constructs the object    |
//| in the main chart window of the current chart at coordinates 0, 0 |
//| with default dimensions                                           |
//+-------------------------------------------------------------------+
CColumnCaptionView::CColumnCaptionView(void) : CCaptionView("ColumnCaption","Caption",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H),m_sort_mode(TABLE_SORT_MODE_NONE),m_sortable(true)
  {
//--- Initialization
   this.Init("Caption");
   this.SetID(0);
   this.SetIndex(-1);
   this.SetName("ColumnCaption");
  }
//+-----------------------------------------------------------------------------+
//| CColumnCaptionView::Parameterized constructor.                              |
//| Construct the object in the specified window of the specified chart with    |
//| the specified text, coordinates, and dimensions                             |
//+-----------------------------------------------------------------------------+
CColumnCaptionView::CColumnCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h) :
   CCaptionView(object_name,text,chart_id,wnd,x,y,w,h),m_sort_mode(TABLE_SORT_MODE_NONE),m_sortable(true)
  {
//--- Initialization
   this.Init(text);
   this.SetID(0);
   this.SetIndex(-1);
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Initialization                               |
//+------------------------------------------------------------------+
void CColumnCaptionView::Init(const string text)
  {
//--- Initialization of the parent object
   CCaptionView::Init(text);

//--- Can be resized
   this.SetResizable(true);
   this.SetMovable(false);
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Draw the object's appearance                 |
//+------------------------------------------------------------------+
void CColumnCaptionView::Draw(const bool chart_redraw)
  {
//--- If the object is outside its container, exit
   if(this.IsOutOfContainer())
      return;

//--- Fill the object with the background color; draw a light vertical line on the left and a dark one on the right
   this.Fill(this.BackColor(),false);
   color clr_dark =this.BorderColor();                                                       // "Dark color"
   color clr_light=this.GetBackColorControl().NewColor(this.BorderColor(), 20, 20, 20);      // "Light color"
   this.m_background.Line(this.AdjX(0),this.AdjY(0),this.AdjX(0),this.AdjY(this.Height()-1),::ColorToARGB(clr_light,this.AlphaBG()));                          // Line on the left
   this.m_background.Line(this.AdjX(this.Width()-1),this.AdjY(0),this.AdjX(this.Width()-1),this.AdjY(this.Height()-1),::ColorToARGB(clr_dark,this.AlphaBG())); // Line on the right

//--- Display the header text
   CLabel::Draw(false);
      
//--- Draw sort direction arrows
   this.DrawSortModeArrow();

//--- Update the background canvas
   this.m_background.Update(false);
   
//--- If specified, update the chart
   if(chart_redraw)
      ::ChartRedraw(this.m_chart_id);
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Draw the sort direction arrow                |
//+------------------------------------------------------------------+
void CColumnCaptionView::DrawSortModeArrow(void)
  {
//--- Set the arrow color for the object's normal and disabled states
   color clr=(!this.IsBlocked() ? this.GetForeColorControl().NewColor(this.ForeColor(),90,90,90) : this.ForeColor());
   switch(this.m_sort_mode)
     {
      //--- Sort in ascending order
      case TABLE_SORT_MODE_ASC   :  
         //--- Clear the drawing area and draw a downward arrow
         this.m_painter.Clear(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),false);
         this.m_painter.ArrowDown(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),clr,this.AlphaFG(),true);
         break;
      //--- Sort in descending order
      case TABLE_SORT_MODE_DESC  :  
         //--- Clear the drawing area and draw an upward arrow
         this.m_painter.Clear(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),false);
         this.m_painter.ArrowUp(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),clr,this.AlphaFG(),true);
         break;
      //--- No sorting
      default : 
         //--- Clear the drawing area
         this.m_painter.Clear(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),false);
         break;
     }
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Reverse the sort direction                   |
//+------------------------------------------------------------------+
void CColumnCaptionView::SetSortModeReverse(void)
  {
   switch(this.m_sort_mode)
     {
      case TABLE_SORT_MODE_ASC   :  this.m_sort_mode=TABLE_SORT_MODE_DESC; break;
      case TABLE_SORT_MODE_DESC  :  this.m_sort_mode=TABLE_SORT_MODE_ASC;  break;
      default                    :  break;
     }
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Return the object's description              |
//+------------------------------------------------------------------+
string CColumnCaptionView::Description(void)
  {
   string nm=this.Name();
   string name=(nm!="" ? ::StringFormat(" \"%s\"",nm) : nm);
   string sort=(this.SortMode()==TABLE_SORT_MODE_ASC ? "ascending" : this.SortMode()==TABLE_SORT_MODE_DESC ? "descending" : "none");
   return ::StringFormat("%s%s ID %d, X %d, Y %d, W %d, H %d, sort %s",ElementDescription((ENUM_ELEMENT_TYPE)this.Type()),name,this.ID(),this.X(),this.Y(),this.Width(),this.Height(),sort);
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Set the column header model                  |
//+------------------------------------------------------------------+
bool CColumnCaptionView::ColumnCaptionModelAssign(CColumnCaption *caption_model)
  {
//--- If an invalid column header model object is passed, report it and return false
   if(caption_model==NULL)
     {
      ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__);
      return false;
     }
//--- Save the column header model
   this.m_column_caption_model=caption_model;
//--- Set the dimensions of the drawing area for the visual representation of the column header
   this.m_painter.SetBound(0,0,this.Width(),this.Height());
//--- Completed successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Print to the log                             |
//  the assigned column header model                                 
//+------------------------------------------------------------------+
void CColumnCaptionView::ColumnCaptionModelPrint(void)
  {
   if(this.m_column_caption_model!=NULL)
      this.m_column_caption_model.Print();
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Add to the list                              |
//  tooltip objects with arrows
//+------------------------------------------------------------------+
bool CColumnCaptionView::AddHintsArrowed(void)
  {
//--- Create the horizontal-offset arrow tooltip
   CVisualHint *hint=this.CreateAndAddNewHint(HINT_TYPE_ARROW_SHIFT_HORZ,DEF_HINT_NAME_SHIFT_HORZ,18,18);
   if(hint==NULL)
      return false;

//--- Set the size of the tooltip image area
   hint.SetImageBound(0,0,hint.Width(),hint.Height());
   
//--- Hide the tooltip and draw its visual appearance
   hint.Hide(false);
   hint.Draw(false);
   
//--- Everything completed successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Display a resize cursor                      |
//+------------------------------------------------------------------+
bool CColumnCaptionView::ShowCursorHint(const ENUM_CURSOR_REGION edge,int x,int y)
  {
   CVisualHint *hint=NULL;          // Pointer to a tooltip
   int hint_shift_x=0;              // Tooltip X offset
   int hint_shift_y=0;              // Tooltip Y offset
   
//--- Depending on the cursor's position at the element's boundaries
//--- Specify the tooltip offsets relative to the cursor coordinates,
//--- Display the required tooltip on the chart and obtain a pointer to this object
   if(edge!=CURSOR_REGION_RIGHT)
      return false;
   
   hint_shift_x=-8;
   hint_shift_y=-12;
   this.ShowHintArrowed(HINT_TYPE_ARROW_SHIFT_HORZ,x+hint_shift_x,y+hint_shift_y);
   hint=this.GetHint(DEF_HINT_NAME_SHIFT_HORZ);

//--- Return the result of adjusting the tooltip's position relative to the cursor
   return(hint!=NULL ? hint.Move(x+hint_shift_x,y+hint_shift_y) : false);
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Handler for resizing by the right edge       |
//+------------------------------------------------------------------+
bool CColumnCaptionView::ResizeZoneRightHandler(const int x,const int y)
  {
//--- Calculate and set the new width of the element
   int width=::fmax(x-this.X()+1,DEF_TABLE_COLUMN_MIN_W);
   if(!this.ResizeW(width))
      return false;
//--- Get a pointer to the tooltip
   CVisualHint *hint=this.GetHint(DEF_HINT_NAME_SHIFT_HORZ);
   if(hint==NULL)
      return false;
//--- Move the tooltip by the specified amounts relative to the cursor
   int shift_x=-8;
   int shift_y=-12;
   
   CTableHeaderView *header=this.m_container;
   if(header==NULL)
      return false;
   
   bool res=header.RecalculateBounds(this.GetBoundNode(),this.Width());
   res &=hint.Move(x+shift_x,y+shift_y);
   if(res)
      ::ChartRedraw(this.m_chart_id);
   return res;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Change the object width                      |
//+------------------------------------------------------------------+
bool CColumnCaptionView::ResizeW(const int w)
  {
   if(!CCanvasBase::ResizeW(w))
      return false;
//--- Clear the drawing area at the previous location
   this.m_painter.Clear(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()),this.m_painter.Width(),this.m_painter.Height(),false);
//--- Set a new drawing area
   this.SetImageBound(this.Width()-14,4,8,11);
   return true;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Mouse button press event handler             |
//+------------------------------------------------------------------+
void CColumnCaptionView::OnPressEvent(const int id,const long lparam,const double dparam,const string sparam)
  {
//--- If the mouse button is released within the right-edge drag area of the element, exit
   if(this.ResizeRegion()==CURSOR_REGION_RIGHT)
      return;
//--- Reverse the sort direction arrow and call the mouse click handler
   if(this.m_sortable)
      this.SetSortModeReverse();
   CCanvasBase::OnPressEvent(id,lparam,dparam,sparam);
   ::EventChartCustom(this.m_chart_id,CHARTEVENT_OBJECT_CLICK,this.ID(),-(10000+this.SortMode()),this.NameFG());
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Save to file                                 |
//+------------------------------------------------------------------+
bool CColumnCaptionView::Save(const int file_handle)
  {
//--- Save the parent object's data
   if(!CButton::Save(file_handle))
      return false;
  
//--- Save the header number
   if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE)
      return false;
//--- Save the sort direction
   if(::FileWriteInteger(file_handle,this.m_sort_mode,INT_VALUE)!=INT_VALUE)
      return false;
//--- Save the sort control flag
   if(::FileWriteInteger(file_handle,this.m_sortable,INT_VALUE)!=INT_VALUE)
      return false;
      
//--- Done successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Load from file                               |
//+------------------------------------------------------------------+
bool CColumnCaptionView::Load(const int file_handle)
  {
//--- Load the parent object's data
   if(!CButton::Load(file_handle))
      return false;
      
//--- Load the header number
   this.m_index=::FileReadInteger(file_handle,INT_VALUE);
//--- Load the sort direction
   this.m_sort_mode=(ENUM_TABLE_SORT_MODE)::FileReadInteger(file_handle,INT_VALUE);
//--- Load the sort control flag
   this.m_sortable=(bool)::FileReadInteger(file_handle,INT_VALUE);
   
//--- Done successfully
   return true;
  }

A la clase se ha añadido una bandera de control de la ordenación y métodos para gestionar esta bandera:

class CColumnCaptionView : public CCaptionView
  {
protected:
   CColumnCaption   *m_column_caption_model;                         // Pointer to the column header model
   ENUM_TABLE_SORT_MODE m_sort_mode;                                 // Table column sorting mode
   bool              m_sortable;                                     // Sort control flag
   
//--- Add tooltip objects with arrows to the list
   virtual bool      AddHintsArrowed(void);
//--- Display the resize cursor
   virtual bool      ShowCursorHint(const ENUM_CURSOR_REGION edge,int x,int y);
   
public:
//--- (1) Set, (2) return the column header model
   bool              ColumnCaptionModelAssign(CColumnCaption *caption_model);
   CColumnCaption   *ColumnCaptionModel(void)                           { return this.m_column_caption_model;        }

//--- Print the assigned column header model to the log
   void              ColumnCaptionModelPrint(void);

//--- (1) Set, (2) return the sortability flag
   void              SetSortableFlag(const bool flag)
                       {
                        this.m_sortable=flag;
                        this.SetSortMode(flag ? TABLE_SORT_MODE_ASC : TABLE_SORT_MODE_NONE);
                       }
   bool              IsSortabe(void)                              const { return this.m_sortable;                    }

//--- (1) Set, (2) return the sorting mode

Ahora podemos configurar una columna para que permita ordenar la tabla según los valores de sus celdas.

En los constructores de la clase, su valor predeterminado se establece en True:

//+------------------------------------------------------------------+
//| CColumnCaptionView::Default constructor. Construct the object    |
//| in the main chart window of the current chart at coordinates 0,0 |
//| with default dimensions                                          |
//+------------------------------------------------------------------+
CColumnCaptionView::CColumnCaptionView(void) : CCaptionView("ColumnCaption","Caption",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H),m_sort_mode(TABLE_SORT_MODE_NONE),m_sortable(true)
  {
//--- Initialization
   this.Init("Caption");
   this.SetID(0);
   this.SetIndex(-1);
   this.SetName("ColumnCaption");
  }
//+-----------------------------------------------------------------------------+
//| CColumnCaptionView::Parameterized constructor.                              |
//| Construct the object in the specified window of the specified chart with    |
//| the specified text, coordinates, and dimensions                             |
//+-----------------------------------------------------------------------------+
CColumnCaptionView::CColumnCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h) :
   CCaptionView(object_name,text,chart_id,wnd,x,y,w,h),m_sort_mode(TABLE_SORT_MODE_NONE),m_sortable(true)
  {
//--- Initialization
   this.Init(text);
   this.SetID(0);
   this.SetIndex(-1);
  }

En el manejador de eventos de pulsación de los botones del ratón, ahora se comprueba la bandera de control de la ordenación y se envía un evento personalizado de clic en el objeto:

//+------------------------------------------------------------------+
//| CColumnCaptionView::Mouse button click event handler             |
//+------------------------------------------------------------------+
void CColumnCaptionView::OnPressEvent(const int id,const long lparam,const double dparam,const string sparam)
  {
//--- If the mouse button is released within the drag area of the element's right edge, exit
   if(this.ResizeRegion()==CURSOR_REGION_RIGHT)
      return;
//--- Change the sort direction arrow to the opposite direction and call the mouse click handler
   if(this.m_sortable)
      this.SetSortModeReverse();
   CCanvasBase::OnPressEvent(id,lparam,dparam,sparam);
   ::EventChartCustom(this.m_chart_id,CHARTEVENT_OBJECT_CLICK,this.ID(),-(10000+this.SortMode()),this.NameFG());
  }

En el evento personalizado, indicamos en lparam el identificador del encabezado y, en dparam, el valor negativo del modo de ordenación incrementado en 10 000, para asegurarnos de que no se trata de una coordenada del cursor. En sparam se indica el nombre del objeto (el nombre del canvas en primer plano). Todo esto permitirá que el programa reciba el evento de clic en el encabezado y determine sus parámetros y el modo de ordenación establecido para él.

En los métodos de gestión de archivos, guardamos y cargamos la bandera de control de la ordenación:

//+------------------------------------------------------------------+
//| CColumnCaptionView::Save to file                                 |
//+------------------------------------------------------------------+
bool CColumnCaptionView::Save(const int file_handle)
  {
//--- Save the parent object's data
   if(!CButton::Save(file_handle))
      return false;
  
//--- Save the header number
   if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE)
      return false;
//--- Save the sort direction
   if(::FileWriteInteger(file_handle,this.m_sort_mode,INT_VALUE)!=INT_VALUE)
      return false;
//--- Save the sort control flag
   if(::FileWriteInteger(file_handle,this.m_sortable,INT_VALUE)!=INT_VALUE)
      return false;
      
//--- Success
   return true;
  }
//+------------------------------------------------------------------+
//| CColumnCaptionView::Load from file                               |
//+------------------------------------------------------------------+
bool CColumnCaptionView::Load(const int file_handle)
  {
//--- Load the parent object's data
   if(!CButton::Load(file_handle))
      return false;
      
//--- Load the header number
   this.m_index=::FileReadInteger(file_handle,INT_VALUE);
//--- Load the sort direction
   this.m_sort_mode=(ENUM_TABLE_SORT_MODE)::FileReadInteger(file_handle,INT_VALUE);
//--- Load the sort control flag
   this.m_sortable=(bool)::FileReadInteger(file_handle,INT_VALUE);
   
//--- Success
   return true;
  }

A partir de esta clase modificada, crearemos una nueva clase de encabezado de fila, también derivada de la clase abstracta de encabezado:

//+------------------------------------------------------------------+
//| Class for the visual representation of the table row header      |
//+------------------------------------------------------------------+
class CRowCaptionView : public CCaptionView
  {
protected:
   
public:
//--- Draw the visual appearance
   virtual void      Draw(const bool chart_redraw);

public:  
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CButton::Compare(node,mode);        }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW);}
  
//--- Initialize a class object
   void              Init(const string text);
   
//--- Return a description of the object
   virtual string    Description(void);
   
//--- Constructors/destructor
                     CRowCaptionView(void);
                     CRowCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h); 
                    ~CRowCaptionView (void){}
  };
//+--------------------------------------------------------------------+
//| CRowCaptionView::Default constructor. Construct the object         |
//| in the main chart window of the current chart at coordinates (0,0) |
//| with default dimensions                                            |
//+--------------------------------------------------------------------+
CRowCaptionView::CRowCaptionView(void) : CCaptionView("RowCaption","Caption",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H)
  {
//--- Initialization
   this.Init("Caption");
   this.SetID(0);
   this.SetIndex(-1);
   this.SetName("RowCaption");
   this.SetTextShiftH(8);
  }
//+----------------------------------------------------------------------------------+
//| CRowCaptionView::Parameterized constructor.                                      |
//| Construct the object in the specified chart window of the specified chart with   |
//| the specified text, coordinates, and dimensions                                  |
//+----------------------------------------------------------------------------------+
CRowCaptionView::CRowCaptionView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h) :
   CCaptionView(object_name,text,chart_id,wnd,x,y,w,h)
  {
//--- Initialization
   this.Init(text);
   this.SetID(0);
   this.SetIndex(-1);
   this.SetTextShiftH(8);
  }
//+------------------------------------------------------------------+
//| CRowCaptionView::Initialization                                  |
//+------------------------------------------------------------------+
void CRowCaptionView::Init(const string text)
  {
//--- Initialize the parent object
   CCaptionView::Init(text);
//--- Fixed dimensions
   this.SetResizable(false);
   this.SetMovable(false);
  }
//+------------------------------------------------------------------+
//| CRowCaptionView::Draw the visual appearance                      |
//+------------------------------------------------------------------+
void CRowCaptionView::Draw(const bool chart_redraw)
  {
//--- If the object is outside its container, exit
   if(this.IsOutOfContainer())
      return;

//--- Fill the object with the background color, draw a light vertical line on the left and a dark one on the right
   this.Fill(this.BackColor(),false);
   this.m_background.Rectangle(this.AdjX(2),this.AdjY(0),this.AdjX(this.Width()-1),this.AdjY(this.Height()-1),::ColorToARGB(this.BorderColor(),this.AlphaBG()));
//--- Update the background canvas
   this.m_background.Update(false);
   
//--- Display the header text
   CLabel::Draw(false);
      
//--- If specified, update the chart
   if(chart_redraw)
      ::ChartRedraw(this.m_chart_id);
  }
//+------------------------------------------------------------------+
//| CRowCaptionView::Return the object's description                 |
//+------------------------------------------------------------------+
string CRowCaptionView::Description(void)
  {
   string nm=this.Name();
   string name=(nm!="" ? ::StringFormat(" \"%s\"",nm) : nm);
   return ::StringFormat("%s%s ID %d, X %d, Y %d, W %d, H %d",ElementDescription((ENUM_ELEMENT_TYPE)this.Type()),name,this.ID(),this.X(),this.Y(),this.Width(),this.Height());
  }
//+------------------------------------------------------------------+
//| CRowCaptionView::Save to a file                                  |
//+------------------------------------------------------------------+
bool CRowCaptionView::Save(const int file_handle)
  {
//--- Save the parent object's data
   if(!CButton::Save(file_handle))
      return false;
  
//--- Save the header number
   if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE)
      return false;
      
//--- Completed successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CRowCaptionView::Load from a file                                |
//+------------------------------------------------------------------+
bool CRowCaptionView::Load(const int file_handle)
  {
//--- Load the parent object's data
   if(!CButton::Load(file_handle))
      return false;
      
//--- Load the header number
   this.m_index=::FileReadInteger(file_handle,INT_VALUE);
   
//--- Completed successfully
   return true;
  }

Esta clase es un poco más sencilla que la clase de encabezado de columna, ya que no requiere ordenación ni la visualización de indicaciones para cambiar el tamaño; tampoco se ha implementado el ajuste de la altura de la fila al modificar la altura del encabezado, a diferencia del ajuste correspondiente que se realiza en el encabezado de columna al modificar su anchura. Aquí se ha omitido todo esto por brevedad, pero puede implementarse más adelante.

Modificaremos la clase de la vista del encabezado de la tabla para establecer la bandera que permite ordenar la tabla.

Añadiremos nuevas variables y métodos para trabajar con la bandera de ordenación:

//+------------------------------------------------------------------+
//| Table header visual representation class                         |
//+------------------------------------------------------------------+
class CTableHeaderView : public CPanel
  {
protected:
   CColumnCaptionView m_temp_caption;                                // Temporary column header object for searching
   CTableHeader     *m_table_header_model;                           // Pointer to the table header model
   bool              m_sortable;                                     // Sort control flag

//--- Create a new column header view object and add it to the list
   CColumnCaptionView *InsertNewColumnCaptionView(const string text, const int x, const int y, const int w, const int h);
   
public:
//--- (1) Set, (2) return the table header model
   bool              TableHeaderModelAssign(CTableHeader *header_model);
   CTableHeader     *GetTableHeaderModel(void)                          { return this.m_table_header_model;       }

//--- Recalculate header areas
   bool              RecalculateBounds(CBound *bound,int new_width);

//--- Print the assigned table header model to the log
   void              TableHeaderModelPrint(const bool detail, const bool as_table=false, const int cell_width=CELL_WIDTH_IN_CHARS);
   
//--- Draw the visual appearance
   virtual void      Draw(const bool chart_redraw);

//--- (1) Set, (2) return the sortability flag
   void              SetSortableFlag(const bool flag);
   bool              IsSortabe(void)                              const { return this.m_sortable;                 }

//--- Set the sort flag for the column header
   void              SetSortedColumnCaption(const uint index);

//--- Get the column header (1) by index, (2) with the sort flag set
   CColumnCaptionView *GetColumnCaption(const uint index);
   CColumnCaptionView *GetSortedColumnCaption(void);
//--- Return the index of the column header with the sort flag set
   int               IndexSortedColumnCaption(void);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CPanel::Compare(node,mode);      }
   virtual bool      Save(const int file_handle)                        { return CPanel::Save(file_handle);       }
   virtual bool      Load(const int file_handle)                        { return CPanel::Load(file_handle);       }
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_HEADER_VIEW); }
   
//--- Custom event handler for an element when the object area is clicked
   virtual void      MousePressHandler(const int id, const long lparam, const double dparam, const string sparam);
  
//--- Initialization of (1) the class object and (2) the object's default colors
   void              Init(void);
   virtual void      InitColors(void);

//--- Constructors/destructor
                     CTableHeaderView(void);
                     CTableHeaderView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h);
                    ~CTableHeaderView (void){}
  };

Por defecto, en los constructores de la clase, la bandera está activada:

//+------------------------------------------------------------------+
//| CTableHeaderView::Default constructor. Construct an object in    |
//| the main chart window of the current chart at coordinates 0,0    |
//| with default dimensions                                          |
//+------------------------------------------------------------------+
CTableHeaderView::CTableHeaderView(void) : CPanel("TableHeader","",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H),m_sortable(true)
  {
//--- Initialization
   this.Init();
  }
//+--------------------------------------------------------------------------------+
//  CTableHeaderView::Parameterized constructor. Construct an object in            |
//| in the specified chart window of the specified chart with the specified text,  |
//| coordinates and dimensions                                                     |
//+--------------------------------------------------------------------------------+
CTableHeaderView::CTableHeaderView(const string object_name,const string text,const long chart_id,const int wnd,const int x,const int y,const int w,const int h) :
   CPanel(object_name,text,chart_id,wnd,x,y,w,h),m_sortable(true)
  {
//--- Initialization
   this.Init();
  }

En el método de configuración del modelo de encabezado, ahora comprobamos esta bandera:

//+------------------------------------------------------------------+
//| CTableHeaderView::Sets the header model                          |
//+------------------------------------------------------------------+
bool CTableHeaderView::TableHeaderModelAssign(CTableHeader *header_model)
  {
//--- If an empty object is passed, report this and return 'false'
   if(header_model==NULL)
     {
      ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__);
      return false;
     }
//--- If the passed header model contains no column headers, report this and return 'false'
   int total=(int)header_model.ColumnsTotal();
   if(total==0)
     {
      ::PrintFormat("%s: Error. Header model does not contain any columns",__FUNCTION__);
      return false;
     }
//--- Store the pointer to the passed table header model and calculate the width of each column header
   this.m_table_header_model=header_model;
   int caption_w=(int)::fmax(::round((double)this.Width()/(double)total),DEF_TABLE_COLUMN_MIN_W);

//--- Loop through the column headers in the table header model
   for(int i=0;i<total;i++)
     {
      //--- Get the next column header model,
      CColumnCaption *caption_model=this.m_table_header_model.GetColumnCaption(i);
      if(caption_model==NULL)
         return false;
      //--- Calculate the coordinate and create a name for the column header area
      int x=caption_w*i;
      string name="CaptionBound"+(string)i;
      //--- Create a new column header area
      CBound *caption_bound=this.InsertNewBound(name,x,0,caption_w,this.Height());
      if(caption_bound==NULL)
         return false;
      caption_bound.SetID(i);
      //--- Create a new visual representation object for the column header
      CColumnCaptionView *caption_view=this.InsertNewColumnCaptionView(caption_model.Value(),x,0,caption_w,this.Height());
      if(caption_view==NULL)
         return false;
      caption_view.SetIndex(i);
      
      //--- Assign the corresponding column header visual representation object to the current column header area
      caption_bound.AssignObject(caption_view);
      caption_view.AssignBoundNode(caption_bound);
      
      //--- For the very first column header, set the ascending sort flag
      if(i==0 && caption_view.IsSortabe())
         caption_view.SetSortMode(TABLE_SORT_MODE_ASC);
     }
//--- All done successfully
   return true;
  }

Método que establece la bandera que permite la ordenación:

//+------------------------------------------------------------------+
//| CTableHeaderView::Sets the sortability flag                      |
//+------------------------------------------------------------------+
void CTableHeaderView::SetSortableFlag(const bool flag)
  {
//--- Save the flag value
   this.m_sortable=flag;
   
//--- In a loop over the number of column headers 
   int total=this.m_list_bounds.Total();
   for(int i=0;i<total;i++)
     {
      //--- retrieve the next column header object and set its sort flag
      CColumnCaptionView *caption_view=this.GetColumnCaption(i);
      if(caption_view!=NULL)
         caption_view.SetSortableFlag(flag);
     }
//--- If the table is sortable, set column 0 as sorted in ascending order
   if(this.m_sortable)
      this.SetSortedColumnCaption(0);

//--- Redraw the header
   this.Draw(true);
  }

Se pasa una bandera al método, que la guarda en una variable y en cada uno de los encabezados de columna. Si la bandera de ordenación pasada tiene el valor True, se establece el sentido ascendente de ordenación para la primera columna.
Una vez establecidas las banderas en todos los encabezados de columna, se vuelve a dibujar todo el encabezado.

En el manejador de eventos personalizados del control, al hacer clic en el área del objeto, realizaremos una búsqueda más exhaustiva del índice del encabezado de columna en el valor de sparam y tendremos en cuenta la bandera de ordenación:

//+------------------------------------------------------------------+
//| CTableHeaderView::Handler for the element's custom event         |
//| when clicking in the object area                                 |
//+------------------------------------------------------------------+
void CTableHeaderView::MousePressHandler(const int id,const long lparam,const double dparam,const string sparam)
  {
//--- Retrieve the table header object name from sparam
   int len=::StringLen(this.NameFG());
   string header_str=::StringSubstr(sparam,0,len);
//--- If the retrieved name does not match the name of this object, it is not our event, so we exit
   if(header_str!=this.NameFG())
      return;
   
//--- Find the column header index in sparam
   string capt_str=::StringSubstr(sparam,len+1);
   string index_str=::StringSubstr(capt_str,6,capt_str.Length()-8);
   
//--- The first character before "FG" (the last digit of the target index)
   int pos=(int)capt_str.Length()-3;
   int end=pos;
   
//--- Search for all digits to the left up to the first non-digit
   while(!::IsStopped() && pos>=0 && capt_str.GetChar(pos)>='0' && capt_str.GetChar(pos)<='9')
      pos--;

//--- Start of the digits of the target index
   int start=pos+1;
//--- If the index digits are not found, exit
   if(start>end)
      return;

//--- Retrieve the index from the string
   index_str=StringSubstr(capt_str,start,end-start+1);

//--- Record the column header index
   int index=(int)::StringToInteger(index_str);
   
//--- Retrieve the column header by index
   CColumnCaptionView *caption=this.GetColumnCaption(index);
   if(caption==NULL)
      return;
   
//--- If the header does not have a sort flag, set the ascending sort flag
   if(caption.IsSortabe() && caption.SortMode()==TABLE_SORT_MODE_NONE)
     {
      this.SetSortedColumnCaption(index);
     }
//--- Send a custom event to the chart with the header index in lparam, the sorting mode in dparam, and the object name in sparam
//--- Since the standard OBJECT_CLICK event passes the cursor coordinates in lparam and dparam, we will pass negative values here
   ::EventChartCustom(this.m_chart_id, (ushort)CHARTEVENT_OBJECT_CLICK, -(10000+index), -(10000+caption.SortMode()), this.NameFG());
   ::ChartRedraw(this.m_chart_id);
  }

A partir de la clase modificada del encabezado horizontal de la tabla, crearemos una nueva clase para el encabezado vertical de la tabla:

//+------------------------------------------------------------------+
//| Visual representation class for the table row header             |
//+------------------------------------------------------------------+
class CTableRowsHeaderView : public CPanel
  {
protected:
   CRowCaptionView   m_temp_caption;                                 // Temporary row header object for searching
   string            m_table_row_columns[];                          // Array of table row headers

//--- Create a new visual representation object for the row header and adds it to the list
   CRowCaptionView *InsertNewRowCaptionView(const string text, const int x, const int y, const int w, const int h);
   
public:
//--- (1) Set the array of table row headers
   bool              TableRowCaptionsAssign(string &captions_array[]);

//--- Recalculate the header areas
   bool              RecalculateBounds(CBound *bound,int new_width);

//--- Print the assigned table header model to the log
   void              TableRowHeaderModelPrint(void)                     { ::ArrayPrint(this.m_table_row_columns);       }
   
//--- Draw the appearance
   virtual void      Draw(const bool chart_redraw);
   
//--- Retrieve the row header by index
   CRowCaptionView  *GetRowCaption(const uint index);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CPanel::Compare(node,mode);            }
   virtual bool      Save(const int file_handle)                        { return CPanel::Save(file_handle);             }
   virtual bool      Load(const int file_handle)                        { return CPanel::Load(file_handle);             }
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW);  }
   
//--- Initialization of (1) a class object and (2) the object's default colors
   void              Init(void);
   virtual void      InitColors(void);

//--- Constructors/destructor
                     CTableRowsHeaderView(void);
                     CTableRowsHeaderView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h);
                    ~CTableRowsHeaderView (void){}
  };
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Default constructor. Create the object     |
//| in the main chart window of the current chart at coordinates 0,0 |
//| with default dimensions                                          |
//+------------------------------------------------------------------+
CTableRowsHeaderView::CTableRowsHeaderView(void) : CPanel("TableRowHeader","",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H)
  {
//--- Initialization
   this.Init();
  }
//+-------------------------------------------------------------------------+
//| CTableRowsHeaderView::Parameterized constructor. Construct an object    |
//| in the specified window of the specified chart with the specified text, |
//| coordinates, and dimensions                                             |
//+-------------------------------------------------------------------------+
CTableRowsHeaderView::CTableRowsHeaderView(const string object_name,const string text,const long chart_id,const int wnd,const int x,const int y,const int w,const int h) :
   CPanel(object_name,text,chart_id,wnd,x,y,w,h)
  {
//--- Initialization
   this.Init();
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Initialization                             |
//+------------------------------------------------------------------+
void CTableRowsHeaderView::Init(void)
  {
//--- Initialize the parent object
   CPanel::Init();
//--- Background color - opaque
   this.SetAlphaBG(255);
//--- Border width
   this.SetBorderWidth(1);
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Initialize the object's default colors     |
//+------------------------------------------------------------------+
void CTableRowsHeaderView::InitColors(void)
  {
//--- Initialize the background colors for the normal and activated states and set the normal-state color as the current background color
   this.InitBackColors(C'230,230,230',C'230,230,230',C'230,230,230',clrWhiteSmoke);
   this.InitBackColorsAct(C'230,230,230',C'230,230,230',C'230,230,230',clrWhiteSmoke);
   this.BackColorToDefault();
   
//--- Initialize the foreground colors for the normal and activated states and set the normal-state color as the current text color
   this.InitForeColors(clrBlack,clrBlack,clrBlack,clrSilver);
   this.InitForeColorsAct(clrBlack,clrBlack,clrBlack,clrSilver);
   this.ForeColorToDefault();
   
//--- Initialize the border colors for the normal and activated states and set the normal-state color as the current border color
   this.InitBorderColors(C'200,200,200',C'200,200,200',C'200,200,200',clrSilver);
   this.InitBorderColorsAct(C'200,200,200',C'200,200,200',C'200,200,200',clrSilver);
   this.BorderColorToDefault();
   
//--- Initialize the border color and foreground color for the disabled element
   this.InitBorderColorBlocked(clrSilver);
   this.InitForeColorBlocked(clrSilver);
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Creates and adds to the list               |
//| a new row header view object                                     |
//+------------------------------------------------------------------+
CRowCaptionView *CTableRowsHeaderView::InsertNewRowCaptionView(const string text,const int x,const int y,const int w,const int h)
  {
//--- Create the object name and return the result of creating a new column header
   string user_name="RowCaptionView"+(string)this.m_list_elm.Total();
   CRowCaptionView *caption_view=this.InsertNewElement(ELEMENT_TYPE_TABLE_ROW_CAPTION_VIEW,text,user_name,x,y,w,h);
   return(caption_view!=NULL ? caption_view : NULL);
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Set the vertical header                    |
//+------------------------------------------------------------------+
bool CTableRowsHeaderView::TableRowCaptionsAssign(string &captions_array[])
  {
//--- Get a pointer to the table object (View)
   CPanel *obj=this.GetContainer();
   if(obj==NULL)
      return false;
   CTableView *table_view=obj.GetContainer();
   if(table_view==NULL)
      return false;
      
//--- From the table object, obtain a pointer to the table row panel
   CPanel *table_area=table_view.GetTableArea();
   if(table_area==NULL)
      return false;
   
//--- Retrieve a list of table rows
   CListElm *list=table_area.GetListAttachedElements();
   int total_rows=list.Total();

//--- Save the passed array of table row headers
   ::ArrayCopy(this.m_table_row_columns,captions_array);
   int total_captions=(int)this.m_table_row_columns.Size();
//---
   int total=::fmax(total_rows,total_captions);
//--- Loop through the number of headers to be created
   for(int i=0;i<total;i++)
     {
      //--- get the next row
      CTableRowView *row=table_area.GetAttachedElementAt(i);
      if(row==NULL)
         continue;
      
      //--- Calculate the coordinate and create the name for the row header area
      int y=row.Height()*i;
      string name="CaptionBound"+(string)i;
      //--- Create a new row header area
      CBound *caption_bound=this.InsertNewBound(name,0,y,this.Width(),row.Height());
      if(caption_bound==NULL)
         return false;
      caption_bound.SetID(row.ID());
      //--- Determine the text for the row header
      //--- If the header array has fewer elements than there are rows in the table, the headers will first take values from the array and then row numbers
      //--- If the header array is empty, all rows will be headed with sequential numbers
      string text=(this.m_table_row_columns.Size()>0 ? (i<(int)this.m_table_row_columns.Size() ? this.m_table_row_columns[i] : string(i+1)) : string(i+1));
      //--- Create a new visual representation object for the row header
      CRowCaptionView *caption_view=this.InsertNewRowCaptionView(text,0,y,this.Width(),row.Height());
      if(caption_view==NULL)
         return false;
      caption_view.SetIndex(i);
      
      //--- Assign the appropriate row header visual representation object to the current row header area
      caption_bound.AssignObject(caption_view);
      caption_view.AssignBoundNode(caption_bound);
     }
//--- Everything completed successfully
   return true;
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Recalculate row header areas               |
//+------------------------------------------------------------------+
bool CTableRowsHeaderView::RecalculateBounds(CBound *bound,int new_width)
  {
//--- If an empty area object is passed, or if its width has not changed, return false
   if(bound==NULL || bound.Width()==new_width)
      return false;
      
//--- Get the index of the area in the list
   int index=this.m_list_bounds.IndexOf(bound);
   if(index==WRONG_VALUE)
      return false;

//--- Calculate the offset and, if there is none, return false
   int delta=new_width-bound.Width();
   if(delta==0)
      return false;

//--- Change the width of the current area and of the object assigned to it
   bound.ResizeW(new_width);
   CElementBase *assigned_obj=bound.GetAssignedObj();
   if(assigned_obj!=NULL)
      assigned_obj.ResizeW(new_width);

//--- Get the next area after the current one
   CBound *next_bound=this.m_list_bounds.GetNextNode();
//--- Recalculate the X coordinates for all subsequent areas
   while(!::IsStopped() && next_bound!=NULL)
     {
      //--- Shift the area by the delta value
      int new_x = next_bound.X()+delta;
      int prev_width=next_bound.Width();
      next_bound.SetX(new_x);
      next_bound.Resize(prev_width,next_bound.Height());
      
      //--- If there is an object assigned to the area, update its position
      CElementBase *assigned_obj=next_bound.GetAssignedObj();
      if(assigned_obj!=NULL)
        {
         assigned_obj.Move(assigned_obj.X()+delta,assigned_obj.Y());
         
         //--- This code block is part of the effort to find and eliminate artifacts that occur when dragging headers
         CCanvasBase *base_obj=assigned_obj.GetContainer();
         if(base_obj!=NULL)
           {
            if(assigned_obj.X()>base_obj.ContainerLimitRight())
               assigned_obj.Hide(false);
            else
               assigned_obj.Show(false);
           }
        }
      //--- Move to the next area
      next_bound=this.m_list_bounds.GetNextNode();
     }
     
//--- Calculate the new table header width based on the width of the column headers
   int header_width=0;
   for(int i=0;i<this.m_list_bounds.Total();i++)
     {
      CBound *bound=this.GetBoundAt(i);
      if(bound!=NULL)
         header_width+=bound.Width();
     }

//--- If the calculated table header width differs from the current width, change the width
   if(header_width!=this.Width())
     {
      if(!this.ResizeW(header_width))
         return false;
     }

//--- Get a pointer to the table object (View)
   CPanel *obj=this.GetContainer();
   if(obj==NULL)
      return false;
   CTableView *table_view=obj.GetContainer();
   if(table_view==NULL)
      return false;

//--- From the table object, get a pointer to the table row panel
   CPanel *table_area=table_view.GetTableArea();
   if(table_area==NULL)
      return false;
   
//--- Resize the table row panel to match the total width of the column headers
   if(!table_area.ResizeW(header_width))
      return false;
   
//--- Get the list of table rows and loop through all rows
   CListElm *list=table_area.GetListAttachedElements();
   int total=list.Total();
   for(int i=0;i<total;i++)
     {
      //--- Get the next table row
      CTableRowView *row=table_area.GetAttachedElementAt(i);
      if(row!=NULL)
        {
         //--- Resize the row to fit the panel size and recalculate the cell areas
         row.ResizeW(table_area.Width());
         row.RecalculateBounds(&this.m_list_bounds);
        }
     }
//--- Redraw all table rows
   table_area.Draw(false);
   return true;
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Get the row header by index                |
//+------------------------------------------------------------------+
CRowCaptionView *CTableRowsHeaderView::GetRowCaption(const uint index)
  {
//--- Get the row header area by index
   CBound *capt_bound=this.GetBoundAt(index);
   if(capt_bound==NULL)
      return NULL;
//--- From the row header area, return a pointer to the attached row header object
   return capt_bound.GetAssignedObj();
  }
//+------------------------------------------------------------------+
//| CTableRowsHeaderView::Draw the visual appearance                 |
//+------------------------------------------------------------------+
void CTableRowsHeaderView::Draw(const bool chart_redraw)
  {
//--- Fill the object with the background color, draw the row line, and update the background canvas
   this.Fill(this.BackColor(),false);
   this.m_background.Line(this.AdjX(0),this.AdjY(this.Height()-1),this.AdjX(this.Width()-1),this.AdjY(this.Height()-1),::ColorToARGB(this.BorderColor(),this.AlphaBG()));
   this.m_background.Update(false);
   
//--- Draw the row headers
   int total=this.m_list_bounds.Total();
   for(int i=0;i<total;i++)
     {
      //--- Get the row header object by the loop index
      CRowCaptionView *caption_view=this.GetRowCaption(i);
      //--- Draw the visual representation of the row header
      if(caption_view!=NULL)
        {
         caption_view.Draw(false);
        }
     }
//--- If specified, update the chart
   if(chart_redraw)
      ::ChartRedraw(this.m_chart_id);
  }

Esta clase es una versión ligeramente simplificada de la clase del encabezado de columnas de la tabla. La clase no utiliza el modelo de encabezado vertical, sino un array convencional con los nombres de los encabezados de fila. Al crear una tabla, hay que indicar un array de nombres de filas y se crearán sus encabezados. Si se pasa un array vacío, se insertarán los números de orden como texto en los encabezados de fila.
Todos los métodos de esta clase están comentados con bastante detalle y se pueden estudiar de forma autónoma, teniendo en cuenta que la clase del encabezado vertical reproduce la lógica de la clase del encabezado horizontal de la tabla examinada anteriormente, una lógica que ya debería resultar familiar por los artículos anteriores de esta serie.

Vamos a modificar la clase de la vista de la tabla CTableView. Declararemos nuevas variables y métodos:

//+------------------------------------------------------------------+
//| Table visual representation class                                |
//+------------------------------------------------------------------+
class CTableView : public CPanel
  {
private:
   int               m_rows_header_panel_w;        // Width when creating the table row header panel
   
protected:
//--- Retrieved table data
   CTable           *m_table_obj;                  // A pointer to a table object (includes table and header models)
   CTableModel      *m_table_model;                // A pointer to the table model (obtained from CTable)
   CTableHeader     *m_header_model;               // A pointer to the table header model (obtained from CTable)
   
//--- View component data
   CPanel           *m_header_panel;               // Panel for holding the table header
   CTableHeaderView *m_header_view;                // Pointer to the table header (View)
   CPanel           *m_rows_header_panel;          // Panel for holding the table row header
   CTableRowsHeaderView *m_rows_header_view;       // Pointer to the table row header (View)
   CPanel           *m_table_area;                 // Panel for holding table rows
   CContainer       *m_table_area_container;       // Container for holding the panel with table rows
   bool              m_sortable;                   // Table sortability flag
   
//--- (1) Set, (2) return the table model
   bool              TableModelAssign(CTableModel *table_model);
   CTableModel      *GetTableModel(void)                                { return this.m_table_model;           }
   
//--- (1) Set, (2) return the table header model
   bool              HeaderModelAssign(CTableHeader *header_model);
   CTableHeader     *GetHeaderModel(void)                               { return this.m_header_model;          }
   
//--- (1) Set the required size of the row header panel, (2) return the width of the table row header
   void              SetRowsHeaderPanelSize(const int width)            { this.m_rows_header_panel_w=width;    }
   int               RowsHeaderWidth(void) const
                       {
                        return(this.m_rows_header_view!=NULL ? this.m_rows_header_view.Width() : 0);
                       }

//--- Create an object from the model: (1) a table, (2–3) a header, (4) update the modified table
   bool              CreateTable(void);
   bool              CreateHeader(void);
public:
   bool              CreateRowsHeader(string &captions_array[]);
   bool              UpdateTable(void);
   

//--- (1) Set, (2) return a table object
   bool              TableObjectAssign(CTable *table_obj);
   CTable           *GetTableObj(void)                                  { return this.m_table_obj;             }

//--- Return (1–2) the header, (3) the table placement area, (4) the table area container
   CTableHeaderView *GetHeader(void)                                    { return this.m_header_view;           }
   CTableRowsHeaderView *GetRowsHeader(void)                            { return this.m_rows_header_view;      }
   CPanel           *GetTableArea(void)                                 { return this.m_table_area;            }
   CContainer       *GetTableAreaContainer(void)                        { return this.m_table_area_container;  }

//--- Print the assigned model for (1) the table, (2) the header, and (3) the table object to the log
   void              TableModelPrint(const bool detail);
   void              HeaderModelPrint(const bool detail, const bool as_table=false, const int cell_width=CELL_WIDTH_IN_CHARS);
   void              TablePrint(const int column_width=CELL_WIDTH_IN_CHARS);
   
//--- Retrieve the column header (1) by index, (2) with the sort flag
   CColumnCaptionView *GetColumnCaption(const uint index)
                       { return(this.GetHeader()!=NULL ? this.GetHeader().GetColumnCaption(index) : NULL);     }
   CColumnCaptionView *GetSortedColumnCaption(void)
                       { return(this.GetHeader()!=NULL ? this.GetHeader().GetSortedColumnCaption(): NULL);     }

//--- Return a visual representation object for the specified (1) row or (2) cell
   CTableRowView    *GetRowView(const uint index)
                       { return(this.GetTableArea()!=NULL ? this.GetTableArea().GetAttachedElementAt(index) : NULL); }
   CTableCellView   *GetCellView(const uint row,const uint col)
                       { return(this.GetRowView(row)!=NULL ? this.GetRowView(row).GetCellView(col) : NULL);    }
                       
//--- Return the number of table rows
   int               RowsTotal(void)
                       { return(this.GetTableArea()!=NULL ? this.GetTableArea().AttachedElementsTotal() : 0);  }
                       
//--- Return the number of cells in the specified table row
   int               CellsInRow(const uint row)
                       { return(this.GetRowView(row)!=NULL ? this.GetRowView(row).CellsTotal() : 0);           }

//--- Set the row highlighting method
   void              SetRowsHighlightMode(const ENUM_ROWS_HIGHLIGHT_MODE mode);
   
//--- (1) Set, (2) return the table sortability flag
   void              SetSortable(const bool flag);
   bool              IsSortable(void)                             const { return this.m_sortable;              }
   
//--- Draw the appearance
   virtual void      Draw(const bool chart_redraw);
   
//--- Virtual methods: (1) comparison, (2) saving to a file, (3) loading from a file, (4) object type
   virtual int       Compare(const CObject *node,const int mode=0)const { return CPanel::Compare(node,mode);   }
   virtual bool      Save(const int file_handle);
   virtual bool      Load(const int file_handle);
   virtual int       Type(void)                                   const { return(ELEMENT_TYPE_TABLE_VIEW);     }
   
//--- Custom event handler for an element when the object area is clicked
   virtual void      MousePressHandler(const int id, const long lparam, const double dparam, const string sparam);
   
//--- Sort the table by column value and sort direction
   bool              Sort(const uint column,const ENUM_TABLE_SORT_MODE sort_mode);
  
//--- Initialization of (1) the class object and (2) the object's default colors
   void              Init(void);

//--- Constructors/destructor
                     CTableView(void);
                     CTableView(const string object_name, const string text, const long chart_id, const int wnd, const int x, const int y, const int w, const int h);
                    ~CTableView (void){}
  };

En los constructores de la clase, inicializamos nuevas variables:

//+-----------------------------------------------------------------------+
//| CTableView::Default constructor.                                      |
//| Construct an element in the main chart window of the current chart    |
//| at coordinates 0,0 with default dimensions                            |
//+-----------------------------------------------------------------------+
CTableView::CTableView(void) : CPanel("TableView","",::ChartID(),0,0,0,DEF_PANEL_W,DEF_PANEL_H),
   m_table_model(NULL),m_header_model(NULL),m_table_obj(NULL),m_header_view(NULL),m_rows_header_view(NULL),
   m_table_area(NULL),m_table_area_container(NULL),m_rows_header_panel_w(0),m_sortable(true)
  {
//--- Initialization
   this.Init();
  }
//+-----------------------------------------------------------------------------+
//| CTableView::Parameterized constructor.                                      |
//| Construct an element in the specified chart window of the specified chart   |
//| with the specified text, coordinates, and dimensions                        |
//+-----------------------------------------------------------------------------+
CTableView::CTableView(const string object_name,const string text,const long chart_id,const int wnd,const int x,const int y,const int w,const int h) :
   CPanel(object_name,text,chart_id,wnd,x,y,w,h),m_table_model(NULL),m_header_model(NULL),m_rows_header_view(NULL),m_table_obj(NULL),m_header_view(NULL),
   m_table_area(NULL),m_table_area_container(NULL),m_rows_header_panel_w(0),m_sortable(true)
  {
//--- Initialization
   this.Init();
  }

En el método de inicialización se crea un objeto de tabla con todos sus componentes: los paneles con los encabezados de la tabla y el contenedor con el panel de filas de la tabla. Ahora los encabezados de la tabla se encuentran en sus propios paneles para facilitar su desplazamiento con recorte simultáneo en los límites del panel, ya que es el panel el que implementa la funcionalidad de recorte de los elementos adjuntos cuando estos sobresalen de sus límites:

//+------------------------------------------------------------------+
//| CTableView::Initialization                                       |
//+------------------------------------------------------------------+
void CTableView::Init(void)
  {
//--- Parent object initialization
   CPanel::Init();
//--- Border width, opacity
   this.SetBorderWidth(1);
   this.SetAlphaBG(255);
   this.SetAlphaFG(255);
//--- Initialize the panel background colors and set the current background color
   this.InitBackColors(C'230,230,230',C'230,230,230',C'230,230,230',clrSilver);
   this.BackColorToDefault();
//--- Initialize the panel border colors and set the current border color
   this.InitBorderColors(C'180,180,180',C'180,180,180',C'180,180,180',clrSilver);
   this.BorderColorToDefault();
   
//--- X-coordinate offset for the header and table rows (width of the vertical row header)
   int dx=(int)::StringToInteger(this.Text());

   this.m_rows_header_panel_w=dx;
   this.SetText("");
   if(dx>DEF_TABLE_ROWS_HEADER_W)
      dx+=12;
   
//--- Coordinates and dimensions of the table header panel (horizontal header)
   int x=1+dx;
   int y=1;
   int w=this.Width()-2-dx;
   int h=DEF_TABLE_HEADER_H;
//--- Create a panel for the table header
   this.m_header_panel=this.InsertNewElement(ELEMENT_TYPE_PANEL,"","TableHeaderPanel",x,y,w,h);
   if(this.m_header_panel==NULL)
      return;
//--- Initialize the panel background colors and set the current background color
   this.m_header_panel.InitBackColors(C'230,230,230',C'230,230,230',C'230,230,230',clrSilver);
   this.m_header_panel.BackColorToDefault();
   this.m_header_panel.SetBorderWidth(0);
   this.m_header_panel.SetAlphaBG(255);
//--- Create a table header
   this.m_header_view=this.m_header_panel.InsertNewElement(ELEMENT_TYPE_TABLE_HEADER_VIEW,"","TableHeader",0,0,this.m_header_panel.Width(),this.m_header_panel.Height());
   if(this.m_header_view==NULL)
      return;
   this.m_header_view.SetBorderWidth(0);
   
//--- Coordinates and dimensions of the panel for the table row header (vertical header)
   x=1;
   y=DEF_TABLE_HEADER_H;
   w=(dx>0 ? dx : 1);
   h=this.Height()-2-DEF_TABLE_HEADER_H;
//--- Create a panel
   this.m_rows_header_panel=this.InsertNewElement(ELEMENT_TYPE_PANEL,"","TableRowsHeaderPanel",x,y,w,h);
   if(this.m_rows_header_panel==NULL)
      return;
//--- Initialize the panel's background color and set it as the current background color
   this.m_rows_header_panel.InitBackColors(C'230,230,230',C'230,230,230',C'230,230,230',clrSilver);
   this.m_rows_header_panel.BackColorToDefault();
   this.m_rows_header_panel.SetBorderWidth(0);
   this.m_rows_header_panel.SetAlphaBG(255);
//--- Create the table row header
   this.m_rows_header_view=this.m_rows_header_panel.InsertNewElement(ELEMENT_TYPE_TABLE_ROWS_HEADER_VIEW,"","TableRowsHeader",0,0,this.m_rows_header_panel.Width(),this.m_rows_header_panel.Height());
   if(this.m_rows_header_view==NULL)
      return;
   this.m_rows_header_view.SetBorderWidth(0);
   this.m_rows_header_view.SetAlphaBG(0);
   if(this.m_rows_header_panel_w==0)
      this.m_rows_header_view.Hide(false);
   
//--- Coordinates and dimensions of the container that will hold the table row panel
   x=1+dx;
   y=1+DEF_TABLE_HEADER_H;
   w=this.Width()-2-dx;
   h=this.Height()-2-DEF_TABLE_HEADER_H;
//--- Create a container
   this.m_table_area_container=this.InsertNewElement(ELEMENT_TYPE_CONTAINER,"","TableAreaContainer",x,y,w,h);
   if(this.m_table_area_container==NULL)
      return;
   this.m_table_area_container.SetBorderWidth(0);
   this.m_table_area_container.SetScrollable(true);
   
//--- Attach the panel for storing table rows to the container
   this.m_table_area=this.m_table_area_container.InsertNewElement(ELEMENT_TYPE_PANEL,"","TableAreaPanel",0,0,this.m_table_area_container.Width()-0,this.m_table_area_container.Height()-0);

   if(m_table_area==NULL)
      return;
   this.m_table_area.SetBorderWidth(0);
  }

Método que crea el objeto del encabezado vertical:

//+------------------------------------------------------------------+
//| CTableView::Create a table row header object                     |
//+------------------------------------------------------------------+
bool CTableView::CreateRowsHeader(string &captions_array[])
  {
   if(this.m_rows_header_view==NULL)
     {
      ::PrintFormat("%s: Error. Table rows header object not created",__FUNCTION__);
      return false;
     }
   return this.m_rows_header_view.TableRowCaptionsAssign(captions_array);
  }

Al método se le pasa un array con los nombres de los encabezados de fila y este devuelve el resultado de asignar dicho array al objeto del encabezado vertical de la clase CTableRowsHeaderView.

Vamos a mejorar el método de dibujo:

//+------------------------------------------------------------------+
//| CTableView::Render the appearance                                |
//+------------------------------------------------------------------+
void CTableView::Draw(const bool chart_redraw)
  {
//--- Draw the base
   CPanel::Draw(false);
//--- Draw the header and table rows
   if(this.m_header_view!=NULL)
      this.m_header_view.Draw(false);
   if(this.m_table_area_container!=NULL)
      this.m_table_area_container.Draw(false);
      
//--- Set the offset and dimensions of the image area
   int x=this.m_rows_header_panel.Width()-16;
   int y=this.m_header_panel.Height()-16;
   int w=11;
   int h=w;
//--- Clear the area and draw the corner
   m_painter.Clear(x,y,w,h,false);
   m_painter.TriangleRB(x,y,w,h,BorderColor(),AlphaFG(),true);
      
//--- If specified, update the chart
   if(chart_redraw)
      ::ChartRedraw(this.m_chart_id);
  }

Ahora, además de dibujar el encabezado y el contenedor con el panel de filas de la tabla, el método dibuja también un triángulo relleno en la esquina superior izquierda del panel.

Método que establece el modo de resaltado de filas:

//+------------------------------------------------------------------+
//| CTableView::Set the row highlighting mode                        |
//+------------------------------------------------------------------+
void CTableView::SetRowsHighlightMode(const ENUM_ROWS_HIGHLIGHT_MODE highlight_mode)
  {
   int total=this.RowsTotal();
   for(int i=0;i<total;i++)
     {
      CTableRowView *row=this.GetRowView(i);
      if(row!=NULL)
         row.SetHighlightMode(highlight_mode);
     }
  }

En el bucle que recorre el número de filas de la tabla, obtenemos el siguiente objeto de fila y le aplicamos el modo de resaltado especificado.

Método que establece la bandera que permite ordenar la tabla:

//+------------------------------------------------------------------+
//| CTableView::Set the table sortability flag                       |
//+------------------------------------------------------------------+
void CTableView::SetSortable(const bool flag)
  {
   this.m_sortable=flag;
   CTableHeaderView *header=this.GetHeader();
   if(header!=NULL)
      header.SetSortableFlag(flag);
  }

Se pasa al método la bandera de ordenación, que se establece tanto en la variable m_sortable como en el objeto del encabezado horizontal de la tabla.

En el método de ordenación de la tabla, ahora tenemos en cuenta la bandera que indica si se permite ordenarla:

//+------------------------------------------------------------------+
//| CTableView::Sort the table by column value and sort direction    |
//+------------------------------------------------------------------+
bool CTableView::Sort(const uint column,const ENUM_TABLE_SORT_MODE sort_mode)
  {
//--- If no table model is assigned, report this and return false
   if(this.m_table_model==NULL)
     {
      ::PrintFormat("%s: Error. The table model is not assigned. Please use the TableObjectAssign() method first",__FUNCTION__);
      return false;
     }

//--- If the table has no header or sorting is disabled, return 'false'
   if(this.m_header_model==NULL || !this.m_sortable || sort_mode==TABLE_SORT_MODE_NONE)
      return false;
   
//--- Set the sort direction flag and sort the table model by the specified column and direction
   bool descending=(sort_mode==TABLE_SORT_MODE_DESC);
   this.m_table_model.SortByColumn(column,descending);
//--- Success
   return true;
  }

Ahora vamos a perfeccionar la clase de gestión de tablas.

Para crear tablas que solo tengan un encabezado horizontal superior, se han definido en la clase cuatro métodos públicos y uno protegido; este último crea la tabla y la añade a la lista de tablas creadas. Este último método debe modificarse para que se le pase, además, un array con los nombres de los encabezados de fila. Y añadiremos otros cuatro métodos públicos para crear tablas con dos encabezados: uno horizontal y otro vertical. De este modo, tendremos la posibilidad de crear tablas con encabezado vertical y sin él.

Declararemos métodos adicionales en la clase:

//+------------------------------------------------------------------+
//| Table Management Class                                           | 
//+------------------------------------------------------------------+
class CTableControl : public CPanel
  {
private:
//--- Return the maximum value of an integer array
   bool              ArrayMaximumValue(int &array[],int &value);
//--- Return the maximum text width in the array of row headers
   int               GetMaximumRowCaptionTextSize(string &array_row_captions[]);
   
protected:
   CListObj          m_list_table_model;
//--- Add the table's (1) model object (CTable) and (2) visual representation object (CTableView) to the list
   bool              TableModelAdd(CTable *table_model,const int table_id,const string source);
   CTableView       *TableViewAdd(CTable *table_model,string &row_names[],const string source);
//--- Update the specified column in the specified table
   bool              ColumnUpdate(const string source, CTable *table_model, const uint table, const uint col, const bool cells_redraw);
   
public:
//--- Return (1) the model, (2) the table visual representation object, and (3) the object type
   CTable           *GetTableModel(const uint index)              { return this.m_list_table_model.GetNodeAtIndex(index);  }
   CTableView       *GetTableView(const uint index)               { return this.GetAttachedElementAt(index);               }
   
//--- Create a table based on the provided data
template<typename T>
   CTableView       *TableCreate(T &row_data[][],const string &column_names[],const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(const uint num_rows, const uint num_columns,const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(const matrix &row_data,const string &column_names[],const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(CList &row_data,const string &column_names[],const int table_id=WRONG_VALUE);
template<typename T>
   CTableView       *TableCreate(T &row_data[][],const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(const uint num_rows, const uint num_columns,string &row_names[],const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(const matrix &row_data,const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE);
   CTableView       *TableCreate(CList &row_data,const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE);
   
//--- Return (1) the string value of the specified cell (Model), (2) the specified row, and (3) the table cell (View)
   string            CellValueAt(const uint table, const uint row, const uint col);
   CTableRowView    *GetRowView(const uint table, const uint index);
   CTableCellView   *GetCellView(const uint table, const uint row, const uint col);
   
//--- Set (1) the value, (2) the precision, (3) the time display flags, and (4) the flag for displaying color names for the specified cell (Model + View)
template<typename T>
   void              CellSetValue(const uint table, const uint row, const uint col, const T value, const bool chart_redraw);
   void              CellSetDigits(const uint table, const uint row, const uint col, const int digits, const bool chart_redraw);
   void              CellSetTimeFlags(const uint table, const uint row, const uint col, const uint flags, const bool chart_redraw);
   void              CellSetColorNamesFlag(const uint table, const uint row, const uint col, const bool flag, const bool chart_redraw);

//--- Sets the (1) foreground and (2) background colors for the specified cell (View)
   void              CellSetForeColor(const uint table, const uint row, const uint col, const color clr, const bool chart_redraw);
   void              CellSetBackColor(const uint table, const uint row, const uint col, const color clr, const bool chart_redraw);
   
//--- (1) Set and (2) return the text anchor point for the specified cell (View)
   void              CellSetTextAnchor(const uint table, const uint row, const uint col, const ENUM_ANCHOR_POINT anchor,const bool cell_redraw,const bool chart_redraw);
   ENUM_ANCHOR_POINT CellTextAnchor(const uint table, const uint row, const uint col);
   
//--- Set (1) the precision, (2) the time display flags, (3) the color name display flag, (4) the text anchor point, and (5) the data type for the specified column (View)
   void              ColumnSetDigits(const uint table, const uint col, const int digits, const bool cells_redraw, const bool chart_redraw);
   void              ColumnSetTimeFlags(const uint table, const uint col, const uint flags, const bool cells_redraw, const bool chart_redraw);
   void              ColumnSetColorNamesFlag(const uint table, const uint col, const bool flag, const bool cells_redraw, const bool chart_redraw);
   void              ColumnSetTextAnchor(const uint table, const uint col, const ENUM_ANCHOR_POINT anchor, const bool cells_redraw, const bool chart_redraw);
   void              ColumnSetDatatype(const uint table, const uint col, const ENUM_DATATYPE type, const bool cells_redraw, const bool chart_redraw);

//--- Return the number of (1) rows and (2) cells per row in the specified table
   uint              RowsTotal(const uint table);
   uint              CellsInRow(const uint table,const uint row);

//--- Set (1) the row highlighting mode and (2) the sortability of the specified table
   void              SetRowsHighlightMode(const uint table,const ENUM_ROWS_HIGHLIGHT_MODE highlight_mode);
   void              SetSortable(const uint table,const bool flag);
   
//--- Object type
   virtual int       Type(void)                             const { return(ELEMENT_TYPE_TABLE_CONTROL_VIEW);               }

//--- Constructors/destructor
                     CTableControl(void) { this.m_list_table_model.Clear(); }
                     CTableControl(const string object_name, const long chart_id, const int wnd, const int x, const int y, const int w, const int h);
                    ~CTableControl(void) {}
  };

Analicemos la implementación de los nuevos métodos.

Método que devuelve el valor máximo de un array de enteros:

//+------------------------------------------------------------------+
//| Return the maximum value of an integer array                     |
//+------------------------------------------------------------------+
bool CTableControl::ArrayMaximumValue(int &array[],int &value)
  {
   ::ResetLastError();
   int index=::ArrayMaximum(array);
   if(index<0)
     {
      ::PrintFormat("%s: ArrayMaximum() failed. Error %d",__FUNCTION__,::GetLastError());
      return false;
     }
   value=array[index];
   return true;
  }

Al método se le pasa un array en el que hay que encontrar el valor máximo y una variable en la que se almacenará dicho valor. El método devuelve True y asigna a la variable el valor máximo encontrado en el array.
En caso de error, devuelve False.

Método que devuelve la anchura máxima del texto en un array de encabezados de fila:

//+------------------------------------------------------------------+
//| Return the maximum text width in the array of row headers        |
//+------------------------------------------------------------------+
int CTableControl::GetMaximumRowCaptionTextSize(string &row_captions[])
  {
   int total=(int)row_captions.Size();
   if(total==0)
      return 0;

   int array[]={};
   ::ArrayResize(array,total);
   for(int i=0;i<total;i++)
     {
      string text=row_captions[i];
      text.TrimLeft();
      text.TrimRight();
      array[i]=this.m_foreground.TextWidth(text);
     }
   int value=0;
   return(this.ArrayMaximumValue(array,value) ? value : 0);
  }

Al crear un encabezado vertical, es necesario calcular su anchura de modo que los nombres de todas las filas quepan en los encabezados de fila que se van a crear. Este método determina la anchura máxima del texto en el array de nombres de encabezados de fila que se pasa al método por referencia. En caso de error, el método devuelve 0.

Vamos a modificar el método que crea un nuevo objeto de la vista de la tabla y lo añade a la lista:

//+------------------------------------------------------------------+
//| Create a new object and adds it to the list                      |
//| visual representation of the table (CTableView)                  |
//+------------------------------------------------------------------+
CTableView *CTableControl::TableViewAdd(CTable *table_model,string &row_names[],const string source)
  {
//--- Check the table model object
   if(table_model==NULL)
     {
      ::PrintFormat("%s::%s: Error. An invalid Table Model object was passed",source,__FUNCTION__);
      return NULL;
     }
//--- Get the maximum text width of the row headers
   int w=this.GetMaximumRowCaptionTextSize(row_names);
   if(w>0 && w<DEF_TABLE_ROWS_HEADER_W)
      w=DEF_TABLE_ROWS_HEADER_W;
      
//--- Create a new element—a table visual representation attached to the panel
   CTableView *table_view=this.InsertNewElement(ELEMENT_TYPE_TABLE_VIEW,(string)w,"TableView"+(string)table_model.ID(),1,1,this.Width()-2,this.Height()-2);
   if(table_view==NULL)
     {
      ::PrintFormat("%s::%s: Error. Failed to create Table View object",source,__FUNCTION__);
      return NULL;
     }
//--- Assign the table object (Model) and its identifier to the "Table" (View) graphical element
   table_view.TableObjectAssign(table_model);
   table_view.CreateRowsHeader(row_names);
   table_view.SetID(table_model.ID());
   return table_view;
  }

Ahora se pasa al método, además, un array con los nombres de los encabezados de fila. A continuación, se calcula el ancho del objeto del encabezado vertical de la tabla (o bien 0 si el array está vacío, o bien un ancho no inferior al valor DEF_TABLE_ROWS_HEADER_W). Al crear un objeto de vista de tabla, el ancho calculado del encabezado vertical se pasa al parámetro de texto del panel como un valor de cadena (tras crear la tabla utilizando el ancho del encabezado vertical, se introduce una cadena vacía en el parámetro de texto del panel). Una vez creado el objeto de tabla, se invoca su método para crear el encabezado vertical.

Vamos a modificar cuatro métodos públicos para crear un objeto de vista de tabla:

//| Create a table by specifying a table array and a header array.      | 
//| Determine the number and names of the columns based on column_names |
//| The number of rows is determined by the size of the row_data array, |
//| which is also used to populate the table                            |
//+---------------------------------------------------------------------+
template<typename T>
CTableView *CTableControl::TableCreate(T &row_data[][],const string &column_names[],const int table_id=WRONG_VALUE)
  {
//--- Create a table object based on the specified parameters
   CTable *table_model=new CTable(row_data,column_names);
//--- If errors occur while creating or adding the table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return a table with an empty row header array
   string array[]={};
   return this.TableViewAdd(table_model,array,__FUNCTION__);
  }
//+------------------------------------------------------------------+
//| Create a table with a specified number of columns and rows.      |
//| The columns will have Excel-style names "A", "B", "C", etc.      |
//+------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(const uint num_rows,const uint num_columns,const int table_id=WRONG_VALUE)
  {
   CTable *table_model=new CTable(num_rows,num_columns);
//--- If errors occur while creating or adding the table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return a table with an empty row header array
   string array[]={};
   return this.TableViewAdd(table_model,array,__FUNCTION__);
  }
//+----------------------------------------------------------------------------+
//| Create a table with columns initialized according to column_names          |
//| The number of rows is determined by the row_data parameter of type matrix  |
//+----------------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(const matrix &row_data,const string &column_names[],const int table_id=WRONG_VALUE)
  {
   CTable *table_model=new CTable(row_data,column_names);
//--- If errors occur while creating or adding the table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return a table with an empty row header array
   string array[]={};
   return this.TableViewAdd(table_model,array,__FUNCTION__);
  }
//+-----------------------------------------------------------------------+
//| Create a table by specifying a table array based on                   |
//| the row_data list, which contains objects with structure field data.  | 
//| Determine the number and names of columns based on the number of      |
//| column names in the column_names array                                |
//+-----------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(CList &row_data,const string &column_names[],const int table_id=WRONG_VALUE)
  {
   CTableByParam *table_model=new CTableByParam(row_data,column_names);
//--- If errors occur while creating or adding the table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return a table with an empty row header array
   string array[]={};
   return this.TableViewAdd(table_model,array,__FUNCTION__);
  }

Como ahora el método TableViewAdd() requiere que se le pase un array de encabezados de fila, y aquí se crean tablas sin encabezado vertical, simplemente declaramos un array vacío y lo pasamos al método de creación de una nueva tabla.

Escribiremos cuatro métodos sobrecargados para crear tablas con encabezado vertical:

//+-------------------------------------------------------------------------+
//| Create a table by specifying a table array and an array of row headers. | 
//| Determine the number and names of columns based on column_names         |
//| The number of rows is determined by the size of the row_data array,     |
//| which is also used to populate the table                                |
//+-------------------------------------------------------------------------+
template<typename T>
CTableView *CTableControl::TableCreate(T &row_data[][],const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE)
  {
//--- Create a table object using the specified parameters
   CTable *table_model=new CTable(row_data,column_names);
//--- If there are errors when creating or adding a table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;

//--- Create and return the table
   return this.TableViewAdd(table_model,row_names,__FUNCTION__);
  }
//+------------------------------------------------------------------+
//| Create a table with a specified number of columns and rows.      |
//| The columns will have Excel-style names: "A", "B", "C", etc.     |
//+------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(const uint num_rows,const uint num_columns,string &row_names[],const int table_id=WRONG_VALUE)
  {
   CTable *table_model=new CTable(num_rows,num_columns);
//--- If there are errors when creating or adding a table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return the table
   return this.TableViewAdd(table_model,row_names,__FUNCTION__);
  }
//+----------------------------------------------------------------------------+
//| Create a table with columns initialized according to column_names          |
//| The number of rows is determined by the row_data parameter of type matrix  |
//+----------------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(const matrix &row_data,const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE)
  {
   CTable *table_model=new CTable(row_data,column_names);
//--- If there are errors when creating or adding a table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return the table
   return this.TableViewAdd(table_model,row_names,__FUNCTION__);
  }
//+-----------------------------------------------------------------------+
//| Create a table by specifying the table array based on                 |
//| the row_data list, which contains objects with structure field data.  | 
//| Determine the number and names of columns based on the number         |
//| of column names in the column_names array                             |
//+-----------------------------------------------------------------------+
CTableView *CTableControl::TableCreate(CList &row_data,const string &column_names[],string &row_names[],const int table_id=WRONG_VALUE)
  {
   CTableByParam *table_model=new CTableByParam(row_data,column_names);
//--- If there are errors when creating or adding a table to the list, return NULL
   if(!this.TableModelAdd(table_model,table_id,__FUNCTION__))
      return NULL;
   
//--- Create and return the table
   return this.TableViewAdd(table_model,row_names,__FUNCTION__);
  }

Aquí se pasa a los métodos un array con los nombres de los encabezados de fila, y ese mismo array se pasa al método de creación de un nuevo objeto de tabla.

Método que establece el color de fondo de la celda indicada:

//+------------------------------------------------------------------+
//| Set the background color for the specified cell (View)           |
//+------------------------------------------------------------------+
void CTableControl::CellSetBackColor(const uint table,const uint row,const uint col,const color clr,const bool chart_redraw)
  {
//--- Get the cell's visual representation object
   CTableCellView *cell_view=this.GetCellView(table,row,col);
   if(cell_view==NULL)
      return;
   
//--- Set the cell's background color in the cell visual representation object
//--- Redraw the cell with the chart update flag
   cell_view.SetBackColor(clr);
   cell_view.Draw(chart_redraw);
  }

La lógica del método está completamente comentada en el código.

Método que devuelve el número de filas de la tabla indicada:

//+------------------------------------------------------------------+
//| Return the number of rows in the specified table                 |
//+------------------------------------------------------------------+
uint CTableControl::RowsTotal(const uint table)
  {
   CTableView *table_view=this.GetTableView(table);
   if(table_view==NULL)
     {
      ::PrintFormat("%s: Error. Failed to get CTableView object",__FUNCTION__);
      return NULL;
     }
   return table_view.RowsTotal();
  }

Obtenemos el objeto de la tabla por su índice en la lista y devolvemos el número de filas que contiene.

Método que devuelve el número de celdas de una fila en la tabla indicada:

//+------------------------------------------------------------------+
//| Return the number of cells in a row in the specified table       |
//+------------------------------------------------------------------+
uint CTableControl::CellsInRow(const uint table,const uint row)
  {
   CTableRowView *row_view=this.GetRowView(table,row);
   return(row_view!=NULL ? row_view.CellsTotal() : 0);
  }

Obtenemos una tabla a partir de un índice y devolvemos el número de celdas de la fila indicada de dicha tabla.

Método que establece el modo de resaltado de las filas de la tabla indicada:

//+------------------------------------------------------------------+
//| Set the row highlighting mode for the specified table            |
//+------------------------------------------------------------------+
void CTableControl::SetRowsHighlightMode(const uint table,const ENUM_ROWS_HIGHLIGHT_MODE highlight_mode)
  {
   CTableView *table_view=this.GetTableView(table);
   if(table_view==NULL)
     {
      ::PrintFormat("%s: Error. Failed to get CTableView object",__FUNCTION__);
      return;
     }
   table_view.SetRowsHighlightMode(highlight_mode);
  }

Obtenemos el objeto de la tabla por su índice y establecemos el modo de resaltado de las filas de la tabla.

Método que establece si se permite la ordenación de la tabla indicada:

//+------------------------------------------------------------------+
//| Set sortability for the specified table                          |
//+------------------------------------------------------------------+
void CTableControl::SetSortable(const uint table,const bool flag)
  {
   CTableView *table_view=this.GetTableView(table);
   if(table_view==NULL)
     {
      ::PrintFormat("%s: Error. Failed to get CTableView object",__FUNCTION__);
      return;
     }
   table_view.SetSortable(flag);
  }

Obtenemos el objeto de la tabla por su índice y establecemos la bandera que permite la ordenación por columnas.

Con esto, hemos terminado de modificar todas las clases de tablas de la biblioteca gráfica. Ahora crearemos un indicador que muestre en una tabla la correlación simétrica de los símbolos especificados en los parámetros de entrada.


Indicador de correlación de símbolos en formato de tabla

El indicador se guardará en la carpeta \MQL5\Indicators\Tables\.

Crearemos en ella un nuevo indicador llamado iCorrelationTable.mq5, que mostrará los datos en la subventana del gráfico, con las siguientes propiedades, parámetros de entrada y variables globales:

//+------------------------------------------------------------------+
//|                                            iCorrelationTable.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers   0
#property indicator_plots     0

#define   CHART_FLOAT_WIDTH   750                                    // Opened symbol chart width
#define   CHART_FLOAT_HEIGHT  500                                    // Opened symbol chart height

//+------------------------------------------------------------------+
//| Included libraries                                               |
//+------------------------------------------------------------------+
#include "Controls\Controls.mqh"    // Control library

//--- input parameters
input(name="Bars Total (at least 10)") uint              InpBarsTotal   =  1000;                                                 // Number of data bars for correlation calculation (at least 10)
input(name="Timeframe")                ENUM_TIMEFRAMES   InpTimeframe   =  PERIOD_CURRENT;                                       // Data timeframe for calculating correlation
input(name="Symbols for Correlation")  string            InpSymbols     =  "EURUSD,GBPUSD,USDJPY,USDCHF,AUDUSD,NZDUSD,USDCAD";   // Symbols for calculating correlation

//--- global variables
string   ExtSymbolsArray[];                                          // Array of symbols for calculating correlation
matrix   ExtPricesData;                                              // Symbol data matrix (Close prices)
uint     ExtBarsTotal;                                               // Number of data bars used to calculate the correlation
matrix   ExtCorrelationMatrix;                                       // Matrix of calculated pairwise correlations between all symbols
bool     ExtDataReady;                                               // Data readiness flag for all symbols
long     ExtSymbolsChart;                                            // Identifier of the new chart for correlation symbols
CTableControl *ExtTableCtrl;                                         // A pointer to a CTableControl object
CTableView *ExtTableView;                                            // Pointer to the table visual representation object

En el manejador de eventos OnInit() del indicador, crearemos una lista con los símbolos indicados en los parámetros de entrada y solicitaremos sus datos:

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping

//--- ID of the chart being opened
   ExtSymbolsChart=0;

//--- Find the chart subwindow
   int wnd=ChartWindowFind();

//--- Populate an array of symbols from those specified in the InpSymbols input parameter
   string sep=",";   // a separator as a character
   ushort u_sep;     // separator character code
//--- Get the separator code 
   u_sep=StringGetCharacter(sep,0); 
//--- Extract substrings from the InpSymbols string using the u_sep separator and store them in the ExtSymbolsArray array
   StringSplit(InpSymbols,u_sep,ExtSymbolsArray);
   
//--- Print the set of symbols for calculating the correlation to the log
   Print("\nSymbols Array:");
   ArrayPrint(ExtSymbolsArray);
   
//--- Enable all symbols in Market Watch
   SymbolsSelect(ExtSymbolsArray);

//--- Get symbol data (at least 10 bars) to calculate symbol correlation
   ExtBarsTotal=(InpBarsTotal<10 ? 10 : InpBarsTotal);
   ExtDataReady=GetAndCalculateData(ExtBarsTotal);
   
//--- Create a graphical table control
   int w=500;
   int h=138;
   ExtTableCtrl=new CTableControl("TableControl0",0,wnd,8,8,w-0,h-0);
   if(ExtTableCtrl==NULL)
     {
      Print("Error. Failed to create TableControl object");
      return INIT_FAILED;
     }

//--- There must be one main element on the chart
   ExtTableCtrl.SetAsMain();

//--- You can set the parameters of the created table control
   ExtTableCtrl.SetID(0);                      // Identifier 
   ExtTableCtrl.SetName("Table Control 0");    // Name

//--- If the symbol data and their correlations have been obtained successfully,
//--- create table object 0 (Model + View component) inside the table control
//--- from the ExtCorrelationMatrixSymmetric matrix created above and
//--- the ExtSymbolsArray string array as column headers
   if(ExtDataReady && !CreateTable(ExtTableCtrl))
      return INIT_FAILED;
   
//--- Everything completed successfully
   return(INIT_SUCCEEDED);
  }

Tras solicitar los datos de los símbolos, crearemos un control de tablas. Si se han obtenido correctamente todos los datos de todos los símbolos y se ha creado a partir de ellos una matriz de correlaciones simétrica, generaremos una tabla con esos datos en el control de tablas. Si aún no se han recibido los datos, la bandera ExtDataReady lo señalará y, en ese caso, en OnCalculate() esperaremos a recibir todos los datos solicitados; una vez recibidos en su totalidad y calculada la matriz de correlaciones, crearemos una tabla y, a partir de ahí, solo actualizaremos los datos en la tabla ya creada de símbolos y sus correlaciones:

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int32_t rates_total,
                const int32_t prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int32_t &spread[])
  {
//--- Retrieve data until it is ready
   ExtDataReady=GetAndCalculateData(ExtBarsTotal);
   if(!ExtDataReady)
     {
      Print("The symbol data and their correlations have not yet been obtained. Waiting for the next tick...");
      return 0;
     }
   
//--- If the table has not been created yet
//--- create table object 0 (Model + View component) inside the table control
//--- from the ExtCorrelationMatrixSymmetric matrix created above and
//--- the ExtSymbolsArray string array as column headers
   if(ExtTableView==NULL && !CreateTable(ExtTableCtrl))
      return 0;

//--- Update the data in the table and set the correlation colors
   UpdateTableValuesAndColors(ExtTableCtrl.GetTableView(0),ExtCorrelationMatrix);

//--- return value of prev_calculated for next call
   return(rates_total);
  }

En el manejador de eventos OnDeinit() eliminamos los objetos creados:

//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int32_t reason)
  {
//--- Delete the table control and destroy the library's shared resource manager
   delete ExtTableCtrl;
   CCommonManager::DestroyInstance();
  }

En el temporizador del indicador, cada minuto y medio solicitamos los datos de todos los símbolos almacenados en el array de trabajo:

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//--- Every minute and a half, get symbol data for the symbols in the array
   static int count=0;
   count++;
   if(count>=3000)
     {
      double array[];
      for(int i=0;i<(int)ExtSymbolsArray.Size();i++)
         CopyClose(ExtSymbolsArray[i],InpTimeframe,0,ExtBarsTotal,array);
      count=0;
     }
//--- Call the OnTimer handler of the table control
   ExtTableCtrl.OnTimer();
  }

Se trata de un indicador multidivisa, por lo que es necesario solicitar los datos de los símbolos para "retener" los datos de cada símbolo, de modo que siempre estén actualizados y no haya que esperar a que se vuelvan a cargar.

En el manejador de eventos, detectaremos el clic sobre una fila de la tabla, determinaremos la dirección de la celda de la tabla (fila/columna) a partir del parámetro sparam y abriremos dos gráficos de esos símbolos en una ventana de gráfico independiente:

//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int32_t id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
//--- Call the OnChartEvent handler of the table control
   ExtTableCtrl.OnChartEvent(id,lparam,dparam,sparam);
   if(id>=CHARTEVENT_CUSTOM)
     {
      //--- Convert the ID of the received custom event to standard event values
      ENUM_CHART_EVENT chart_event=ENUM_CHART_EVENT(id-CHARTEVENT_CUSTOM);
      
      //--- If this is a graphical object click event
      if(chart_event==CHARTEVENT_OBJECT_CLICK)
        {
         //--- If the event name (sparam value) contains the table row name (starts with "TableCellView")
         if(StringFind(sparam,"TableCellView")==0)
           {
            //--- Retrieve the row and column numbers from the event parameters
            int row=(int)lparam;
            int col=(int)dparam;
            
            string sep=";";                  // a separator as a character 
            ushort u_sep;                    // separator character code 
            string result[];                 // an array for receiving strings 
            
            //--- Get the separator code and split sparam into substrings
            u_sep=StringGetCharacter(sep,0); 
            int n=StringSplit(sparam,u_sep,result);
            
            //--- There should be three substrings
            if(n==3)
              {
               //--- Get the row symbol and column symbol
               string row_symb=result[1];
               string col_symb=result[2];
               
               //--- If the chart is not open yet, open it
               if(ExtSymbolsChart==0 || !IsExistChart(ExtSymbolsChart))
                  ExtSymbolsChart=OpenCharts(row_symb,col_symb);

               //--- If the chart is already open
               if(ExtSymbolsChart!=0)
                 {
                  //--- Set the symbols for the two chart objects and redraw the chart
                  ObjectSetString(ExtSymbolsChart,"ChartRowSymbol",OBJPROP_SYMBOL,row_symb);
                  ObjectSetString(ExtSymbolsChart,"ChartColSymbol",OBJPROP_SYMBOL,col_symb);
                  ChartRedraw(ExtSymbolsChart);
                 }
              }
           }
        }
     }
  }

Es decir, podemos hacer clic en la celda de la tabla que nos interese, en la que figura el valor de correlación entre dos símbolos (en la intersección de una fila y una columna), y abrir los gráficos de los símbolos en cuestión.

Veamos las funciones que se usan en el indicador.

Función que incluye los símbolos de un array en Observación del Mercado:

//+------------------------------------------------------------------+
//| Add symbols from the array to Market Watch                       |
//+------------------------------------------------------------------+
bool SymbolsSelect(string &array[])
  {
   bool res=true;
   for(int i=0;i<(int)array.Size();i++)
      res &=SymbolSelect(array[i],true);
   return res;
  }

Ahora recorremos el array de símbolos en un bucle e incluimos cada símbolo en Observación del Mercado. La función devuelve el resultado global de la inclusión de los símbolos en Observación del Mercado. Ni aquí ni al crear el array de símbolos a partir de los parámetros de entrada se comprueba si los símbolos existen en el servidor. Esto se ha hecho para simplificar el ejemplo. Por eso, en la configuración hay que indicar símbolos que existan realmente.

Función que devuelve un símbolo a partir de su índice en el array:

//+------------------------------------------------------------------+
//| Return the symbol by array index                                 |
//+------------------------------------------------------------------+
string GetSymbolByIndex(const int index,string &array[])
  {
   int total=(int)array.Size();
   if(index<0 || index>total-1)
      return StringFormat("%s: Error. Invalid index (%d)",__FUNCTION__,index);
   return array[index];
  }

Función que rellena la matriz de datos de los símbolos:

//+------------------------------------------------------------------+
//| Fill the symbol data matrix                                      |
//+------------------------------------------------------------------+
bool SymbolsDataMatrixFill(const ENUM_TIMEFRAMES timeframe,string &array[],matrix &data,const int data_count)
  {
//--- Loop over the number of symbols in the array variable
   int total=(int)array.Size();
   for(int i=0; i<total; i++)
     {
      //--- obtain data_count Close prices
      double close[];
      int copied=CopyClose(array[i], timeframe, 0, data_count, close);
      if(copied!=data_count)
         return false;
      
      //--- write the prices to the matrix row so that cell 0 of the row corresponds to bar 0
      for(int j=0; j<data_count; j++)
        {
         string symbol=GetSymbolByIndex(i,array);
         int    digits=(int)SymbolInfoInteger(symbol,SYMBOL_DIGITS);
         data[i][data_count-1-j]=NormalizeDouble(close[j],digits);
        }
     }
   return true;
  }

A la función se le pasan el marco temporal de los datos obtenidos, un array de símbolos de los que se obtendrán los datos, una matriz en la que se guardarán los datos y la cantidad de datos que se obtendrán de cada uno de los símbolos del array.

Eso sí, existe una limitación: por motivos de brevedad, aquí no se comprueba la cantidad de datos disponibles en el servidor para cada símbolo. Aquí simplemente se utiliza el valor de la configuración del indicador InpBarsTotal, pero siempre un mínimo de 10 barras. Si la función siempre termina con un error, significa que faltan datos para alguno de los símbolos. En este caso, se puede reducir la cantidad de datos solicitados en la variable InpBarsTotal.

Función que calcula la matriz simétrica de correlaciones entre todos los símbolos de un array:

//+------------------------------------------------------------------+
//|Calculate the symmetric correlation matrix between all symbols    |
//+------------------------------------------------------------------+
bool SymbolsCorrelationMatrixSymmetric(const matrix &data, matrix &correlation)
  {
   int symb_total=(int)data.Rows();    // number of symbols

//--- Set the size of the correlation matrix
   if(!correlation.Resize(symb_total,symb_total))
      return false;

//--- Outer loop over all symbols (rows)
   for(int i=0;i<symb_total;i++)
     {
      //--- Get the price time series for symbol i
      vector vi=data.Row(i);
      //--- Inner loop over all symbols (columns)
      for(int j=0;j<symb_total;j++)
        {
         //--- If the symbols in the row and column are the same, this is self-correlation
         if(i==j)
            correlation[i][j]=1.0;
         
         //--- The symbols in the row and column are different
         else
           {
            //--- Get the price time series for symbol j and calculate the correlation between symbols i and j
            vector vj=data.Row(j);
            correlation[i][j]=vi.CorrCoef(vj);
           }
        }
     }
//--- Completed successfully
   return true;
  }

A la función se le pasan una matriz de datos de símbolos previamente rellenada y una matriz en la que se registrarán los valores de correlación entre los símbolos. La lógica de la función se explica en los comentarios del código.

Función que imprime en el registro una matriz simétrica de correlaciones:

//+------------------------------------------------------------------+
//| Print a symmetric correlation matrix to the log                  |
//+------------------------------------------------------------------+
void SymbolsCorrelationMatrixSymmetricPrint(const string &symb_array[],matrix &correlation)
  {
//--- Create and print the header
   Print("Correlation matrix:");
   string header="        ";
   for(int j=0;j<(int)symb_array.Size();j++)
      header+=symb_array[j]+" ";
   Print(header);

//--- Print symbol correlation data
   for(int i=0;i<(int)symb_array.Size();i++)
     {
      string row=symb_array[i]+" ";
      for(int j=0;j<(int)symb_array.Size();j++)
         row+=DoubleToString(correlation[i][j],2)+" ";
      Print(row);
     }
  }

A la función se le pasan una lista de símbolos y la matriz de correlaciones calculada. En dos bucles, imprimimos los símbolos y los valores de correlación entre ellos.

Función que obtiene y calcula todos los datos necesarios sobre los símbolos:

//+------------------------------------------------------------------+
//| Retrieve and calculates all necessary data                       |
//+------------------------------------------------------------------+
bool GetAndCalculateData(uint bars_total)
  {
//--- Retrieve values for the symbol data
   const int symb_total=(int)ExtSymbolsArray.Size();     // number of symbols

//--- Resize the matrix: rows = symbols, columns = bars
   if(!ExtPricesData.Resize(symb_total,bars_total))
     {
      Print("Error. Failed to resize the symbol data matrix");
      return false;
     }

//--- Fill the matrix with the symbols' Close prices and set the data readiness flag
   ExtDataReady=SymbolsDataMatrixFill(InpTimeframe,ExtSymbolsArray,ExtPricesData,bars_total);
   if(!ExtDataReady)
      return false;
      
//--- Calculate a symmetric correlation matrix
   if(!SymbolsCorrelationMatrixSymmetric(ExtPricesData,ExtCorrelationMatrix))
     {
      Print("Error calculating correlation matrix");
      return false;
     }
   return true; 
  }

A la función se le pasa la cantidad de datos solicitados. Por cada uno de los símbolos se solicita la cantidad de datos indicada. Si los datos se han recibido correctamente, se calcula la matriz de correlaciones entre los símbolos. Si la obtención y el cálculo de todos los datos se realizan correctamente, la función devuelve true; en caso contrario, devuelve false. La función debe llamarse repetidamente hasta que se hayan obtenido y calculado todos los datos. Esto se hace primero durante la inicialización y, después, en cada tick. Una vez que se han obtenido y calculado todos los datos, esta función ya no se vuelve a llamar.

Función que crea en el panel una tabla de símbolos con los datos de sus correlaciones:

//+----------------------------------------------------------------------+
//| Create a table of symbols with their correlation data on the panel   |
//+----------------------------------------------------------------------+
bool CreateTable(CTableControl *table_ctrl)
  {
//--- create table object 0 (Model + View component) inside the table control
//--- from the ExtCorrelationMatrixSymmetric matrix created above and
//--- the ExtSymbolsArray string array of symbols as column headers
   ExtTableView=table_ctrl.TableCreate(ExtCorrelationMatrix,ExtSymbolsArray,ExtSymbolsArray);
   if(ExtTableView==NULL)
      return false;
   
//--- Let's center the text in each cell for the columns
   int total=(int)table_ctrl.RowsTotal(0);
   for(int i=0;i<total;i++)
     {
      table_ctrl.ColumnSetTextAnchor(0,i,ANCHOR_CENTER,true,false);
     }
   
//--- Set the table row/cell highlighting mode for individual cells
   table_ctrl.SetRowsHighlightMode(0,ROWS_HIGHLIGHT_MODE_CELLS);
//--- and make the table non-sortable
   table_ctrl.SetSortable(0,false);
   
//--- Let's draw and color the table using symbol correlation colors
   table_ctrl.Draw(false);
   UpdateTableValuesAndColors(table_ctrl.GetTableView(0),ExtCorrelationMatrix);
   
//--- Let's retrieve the table model with index 0 and print it to the log
   CTable *table_model=table_ctrl.GetTableModel(0);
   table_model.Print(7);
   
//--- Everything completed successfully
   return true;
  }

La función crea, dentro del control de tablas, una tabla basada en los datos de los símbolos y las correlaciones entre ellos. En los encabezados de la tabla se indican los nombres de los símbolos tanto en sentido horizontal como vertical. En las celdas de la tabla se indican los valores de correlación entre los símbolos correspondientes a la fila y la columna de cada celda. Cada celda se colorea según el grado de correlación, desde el rojo (correlación -1) pasando por el amarillo (correlación 0) hasta el verde (correlación +1), creando así un mapa de calor de correlaciones.

Función que actualiza los valores y los colores de las celdas de una tabla según una matriz de correlaciones:

//+--------------------------------------------------------------------------------+
//| Update the values and colors of table cells based on the correlation matrix    |
//+--------------------------------------------------------------------------------+
void UpdateTableValuesAndColors(CTableView *table_view, matrix &corr_matrix)
  {
//--- Let's check the validity of the table pointer
   if(table_view==NULL)
      return;

//--- Number of table rows and columns
   int total_row=table_view.RowsTotal();
   int total_col=table_view.CellsInRow(0);

//--- In a loop through the table rows
   for(int r=0; r<total_row; r++)
     {
      //--- retrieve the next row visual representation object
      CTableRowView *row_obj=table_view.GetRowView(r);
      if(row_obj==NULL)
         continue;
      //--- Get the color control
      CColorElement *ce=row_obj.GetBackColorControl();
      if(ce==NULL)
         continue;
      
      //--- In a loop over the number of cells in the row
      for(int c=0; c<total_col; c++)
        {
         //--- get the next cell visual representation object
         CTableCellView *cell=table_view.GetCellView(r,c);
         if(cell==NULL)
            continue;
         
         //--- Get the correlation value from the matrix
         double val=corr_matrix[r][c];
         //--- Update the cell text,
         cell.SetText(DoubleToString(val,2));
         //--- update the cell color
         color new_color=ce.InterpolateColorByCoeff(clrRed,clrYellow,clrGreen,val);
         cell.SetBackColor(new_color);
         
         //--- Redraw the cell (update the chart when processing the last table cell)
         bool flag=(r==total_row-1 && c==total_col-1 ? true : false); 
         cell.Draw(flag);
        }
     }
  }

Toda la lógica de la función se explica detalladamente en los comentarios. La función se ejecuta en cada tick, inmediatamente después de haber recibido correctamente todos los datos y de haber creado la tabla. Al llamar a la función, esta recalcula los valores de correlación entre los símbolos correspondientes a cada celda de la tabla y actualiza los valores y el color de las celdas.

Función que devuelve una bandera que indica si existe un gráfico con el identificador especificado:

//+--------------------------------------------------------------------------------+
//| Return a flag indicating whether a chart with the specified identifier exists  |
//+--------------------------------------------------------------------------------+
bool IsExistChart(const long id)
  {
//--- Variables for chart identifiers 
   long curr_chart=0, prev_chart=0; 
   int i=0; 

//--- Iterate over all charts
   while(!IsStopped() && i<CHARTS_MAX)
     { 
      //--- Get the next chart based on the previous one
      curr_chart=ChartNext(prev_chart);   // prev_chart==0 - get the first chart
      //--- If we have reached the end of the chart list, exit the loop
      if(curr_chart<0)
         break;
      //--- If the chart identifier matches the target one, such a chart exists
      if(curr_chart==id)
         return true;
      //--- Store the current chart ID for the next ChartNext() call
      prev_chart=curr_chart;
      //--- Increment the counter
      i++;
     }
//--- The target chart does not exist
   return false;
  }

Para no abrir una nueva ventana de gráfico cada vez que hacemos clic en las celdas de la tabla, debemos comprobar si sigue existiendo el gráfico abierto anteriormente. Eso es precisamente lo que hace la función.

Función que abre los gráficos de los símbolos:

//+------------------------------------------------------------------+
//| Open charts for symbols                                          |
//+------------------------------------------------------------------+
long OpenCharts(const string row_symb,const string col_symb)
  {
   //--- Set the symbol and timeframe for the new chart 
   string symbol=row_symb; 
   if(symbol==NULL || symbol=="") 
      symbol=Symbol(); 
    
//--- Open a new chart with the specified symbol and timeframe 
   long id=ChartOpen(symbol,PERIOD_CURRENT);
   if(id==0) 
     { 
      Print("ChartOpen() failed. Error ", GetLastError()); 
      return 0; 
     }
//--- Detach the chart and make it empty
   ChartSetInteger(id,CHART_IS_DOCKED,false);
   ChartSetInteger(id,CHART_SHOW,false);

//--- Get the coordinates of the edges of the detached chart
   int top=(int)ChartGetInteger(id,CHART_FLOAT_TOP);
   int bottom=(int)ChartGetInteger(id,CHART_FLOAT_BOTTOM);
   int left=(int)ChartGetInteger(id,CHART_FLOAT_LEFT);
   int right=(int)ChartGetInteger(id,CHART_FLOAT_RIGHT);
   
//--- Set the new width and height of the chart
   ChartSetInteger(id,CHART_FLOAT_RIGHT,left+CHART_FLOAT_WIDTH);
   ChartSetInteger(id,CHART_FLOAT_BOTTOM,top+CHART_FLOAT_HEIGHT);
   
//--- Get the dimensions of the chart in pixels
   int cw=(int)ChartGetInteger(id,CHART_WIDTH_IN_PIXELS);
   int ch=(int)ChartGetInteger(id,CHART_HEIGHT_IN_PIXELS);
   
//--- Set the height for the top and bottom chart objects
   int h0=(int)round(ch/2);
   int h1=ch-h0;
   
//--- Create two chart objects with the row and column symbols on the detached chart
   if(!CreateChartObject(id,"ChartRowSymbol",row_symb,PERIOD_CURRENT,0,0,cw,h0))
      return 0;
   if(!CreateChartObject(id,"ChartColSymbol",col_symb,PERIOD_CURRENT,0,h0-1,cw,h1+1))
      return 0;
      
//--- Update the opened chart and return its ID
   ChartRedraw(id);
   return id;
  }

Esta función abre un gráfico, lo convierte en flotante e impide que se muestre en él el gráfico de precios. A continuación, se crean dos objetos gráficos "Gráfico" y se establecen la anchura, la altura y el nombre del símbolo de cada uno. De esta manera, obtenemos una ventana flotante en la que se muestran dos gráficos. Al hacer clic en una celda de la tabla, se abrirá una ventana de este tipo con los gráficos de precios de los símbolos correspondientes a la celda seleccionada. No se ha implementado el seguimiento de los cambios de tamaño de la ventana flotante para simplificar el ejemplo. Es decir, aunque se modifique el tamaño de la ventana, los gráficos de los símbolos no cambiarán de tamaño.

Función que crea un objeto gráfico "Gráfico" del símbolo indicado:

//+------------------------------------------------------------------+
//| Create a chart object for the specified symbol                   |
//+------------------------------------------------------------------+
bool CreateChartObject(const long chart_id,const string name,const string symbol,const ENUM_TIMEFRAMES timeframe,const int x,const int y,const int w,const int h)
  {
//--- Create a chart object with the specified coordinates and dimensions
//--- and set its properties: symbol, timeframe, coordinates, and dimensions
   if(ObjectCreate(chart_id,name,OBJ_CHART,0,x,y,w,h))
     {
      ObjectSetString(chart_id,name,OBJPROP_SYMBOL,symbol);
      ObjectSetInteger(chart_id,name,OBJPROP_PERIOD,timeframe);
      ObjectSetInteger(chart_id,name,OBJPROP_XDISTANCE,x);
      ObjectSetInteger(chart_id,name,OBJPROP_YDISTANCE,y);
      ObjectSetInteger(chart_id,name,OBJPROP_XSIZE,w);
      ObjectSetInteger(chart_id,name,OBJPROP_YSIZE,h);
      return true;
     }
//--- Error creating a chart object
   return false;
  } 

A la función se le pasa el identificador del gráfico en el que se debe crear el objeto gráfico "Gráfico", el nombre del objeto que se va a crear, el símbolo y el período del gráfico de dicho objeto, así como sus coordenadas y dimensiones. Una vez creado el objeto, se le asignan todas las propiedades indicadas.

Ya está, el indicador está listo.

Ahora compilamos el indicador y lo ejecutamos en el gráfico:

Todas las funciones anunciadas del indicador y de las tablas funcionan correctamente, como se puede ver en la imagen adjunta más arriba.


Conclusión

Hoy hemos perfeccionado las clases de tablas para que se visualicen de forma más clara gracias al encabezado vertical de las filas de la tabla, y hemos analizado el proceso de creación de un indicador que muestra una tabla de correlaciones entre símbolos mediante valores de correlación y un mapa de calor. Este enfoque permite no solo analizar los valores numéricos de la correlación, sino también evaluar visualmente su distribución gracias a una escala de colores. El uso de la interpolación de color para colorear las celdas de una tabla hace que el análisis de los datos resulte más claro e intuitivo, lo cual es especialmente importante cuando se trabaja con grandes volúmenes de información.

Un mapa de calor de correlaciones puede resultar útil en diversas tareas relacionadas con el análisis de los mercados financieros, por ejemplo, para identificar relaciones entre instrumentos, buscar activos con alta correlación o, por el contrario, instrumentos poco correlacionados con el fin de diversificar la cartera.

La tabla implementada, con encabezados verticales y horizontales y coloración dinámica de las celdas, muestra cómo se puede utilizar de forma eficaz el paradigma MVC para crear elementos complejos de la interfaz.
Podemos ampliar fácilmente la funcionalidad de la tabla añadiendo nuevas capacidades sin necesidad de realizar cambios significativos en el código existente.

El indicador creado hoy no solo es una herramienta útil para analizar correlaciones, sino también un ejemplo de cómo se pueden aprovechar las posibilidades de programación de MQL5 para crear elementos de interfaz complejos y funcionales.


Programas utilizados en el artículo:

#
Nombre Tipo
Descripción
1 Tables.mqh Biblioteca de clases Clases para crear un modelo de tabla
2 Base.mqh Biblioteca de clases Clases para crear el objeto base de los controles
3 Controls.mqh Biblioteca de clases Clases de controles
4 iCorrelationTable.mq5 Indicador de prueba Indicador para mostrar en una tabla la correlación entre símbolos
5 MQL5.zip Archivo comprimido Archivo comprimido que contiene los archivos indicados anteriormente, para descomprimir en el directorio MQL5 del terminal de cliente

Todos los archivos creados se adjuntan al artículo para su estudio independiente. El archivo comprimido se puede descomprimir en la carpeta del terminal, y todos los archivos quedarán ubicados en la carpeta correspondiente: \MQL5\Indicators\Tables\.

El código fuente completo del proyecto, con todos los archivos descritos en el artículo, está disponible en el repositorio.


Traducción del ruso hecha por MetaQuotes Ltd.
Artículo original: https://www.mql5.com/ru/articles/20596

Archivos adjuntos |
Tables.mqh (272.47 KB)
Base.mqh (305.36 KB)
Controls.mqh (928.8 KB)
MQL5.zip (146.27 KB)
Utilizando redes neuronales en MetaTrader Utilizando redes neuronales en MetaTrader
En el artículo se muestra la aplicación de las redes neuronales en los programas de MQL, usando la biblioteca de libre difusión FANN. Usando como ejemplo una estrategia que utiliza el indicador MACD se ha construido un experto que usa el filtrado con red neuronal de las operaciones. Dicho filtrado ha mejorado las características del sistema comercial.
Algoritmo de evolución de cristales de élite — Elite Crystal Evolution Algorithm (Inspirado en el CEO): Teoría Algoritmo de evolución de cristales de élite — Elite Crystal Evolution Algorithm (Inspirado en el CEO): Teoría
Presentamos un nuevo algoritmo poblacional original, el ECEA, inspirado en el proceso de congelación del agua y que adapta las ideas del algoritmo Crystal Energy Optimizer (CEO), con búsqueda en grafos, a problemas generales de optimización. El algoritmo utiliza un grupo de élite dinámico, tres estrategias de búsqueda y un mecanismo de diversificación periódica.
Particularidades del trabajo con números del tipo double en MQL4 Particularidades del trabajo con números del tipo double en MQL4
En estos apuntes hemos reunido consejos para resolver los errores más frecuentes al trabajar con números del tipo double en los programas en MQL4.
Creación de indicadores personalizados en MQL5 (Parte 1): Desarrollo de un indicador de tendencia basado en pivotes con gradiente de Canvas Creación de indicadores personalizados en MQL5 (Parte 1): Desarrollo de un indicador de tendencia basado en pivotes con gradiente de Canvas
En este artículo, creamos un indicador de tendencia basado en pivotes (Pivot-Based Trend Indicator) en MQL5 que calcula líneas pivote rápidas y lentas para períodos definidos por el usuario, detecta la dirección de la tendencia en función de la posición del precio respecto a dichas líneas y señala el inicio de las tendencias con flechas, con la opción de prolongar las líneas más allá de la barra actual. El indicador permite una visualización dinámica con líneas separadas para las tendencias alcistas y bajistas en colores personalizables, líneas rápidas de puntos que cambian de color cuando cambia la tendencia y un relleno gradiente opcional entre líneas, utilizando un objeto de canvas para resaltar mejor las zonas de tendencia.