Tabellen nach dem MVC-Paradigma in MQL5: Integration der Modellkomponente in die Ansichtskomponente
Inhaltsverzeichnis
- Einleitung
- Bibliotheksklassen verfeinern
- Tabellenzellenklasse (Ansicht)
- Tabellenzeilenklasse (Ansicht)
- Spaltenüberschriftenklasse der Tabelle (Ansicht)
- Tabellenkopfklasse (Ansicht)
- Tabellenklasse (Ansicht)
- Überprüfung des Ergebnisses
- Fazit
Einleitung
Im Artikel „Tabellen- und Tabellenkopfklassen auf Basis eines Tabellenmodells in MQL5: Anwendung des MVC-Konzepts“ haben wir die Erstellung der Tabellenmodellklasse abgeschlossen (im MVC-Konzept entspricht diese der Modellkomponente). Als Nächstes entwickelten wir eine Bibliothek mit einfachen Steuerelementen, auf deren Grundlage sich Steuerelemente erstellen lassen, die sich hinsichtlich ihres Zwecks und ihrer Komplexität völlig unterscheiden. Insbesondere die Ansichtskomponente zum Erstellen des TableView-Steuerelements.
In diesem Artikel wird die Umsetzung der Interaktion zwischen der Modellkomponente und der Ansichtskomponente behandelt. Mit anderen Worten: Wir werden heute tabellarische Daten mit ihrer grafischen Darstellung in einem einzigen Steuerelement kombinieren.
Das Steuerelement wird auf Basis der Objektklasse „Panel“ erstellt und besteht aus mehreren Elementen:
- Ein Panel bildet die Basis, auf der der Tabellenkopf und der Datenbereich der Tabelle angebracht sind;
- Ein Panel dient als Tabellenkopf und besteht aus mehreren Elementen: Spaltenüberschriften, die auf Basis der Objektklasse „Button“ erstellt werden;
- Ein Container nimmt die Tabellendaten auf und ermöglicht das Scrollen des Inhalts;
- Panel ist ein Panel zur Anordnung von Tabellenzeilen (es ist an den Container (Punkt 3) angehängt und lässt sich mit dessen Bildlaufleisten verschieben, wenn es über die Grenzen des Containers hinausragt);
- Panel – Tabellenzeile ist ein Panel, auf dem Tabellenzellen gezeichnet werden können und das an das Panel (Punkt 4) angehängt ist. Die Anzahl dieser Objekte entspricht der Anzahl der Tabellenzeilen;
- Die Tabellenzellenklasse ist eine neue Klasse, die das Zeichnen an vorgegebenen Koordinaten auf der angegebenen Zeichenfläche (CCanvas) ermöglicht. Ein Objekt dieser Klasse wird an ein Tabellenzeilenobjekt (Punkt 5) angehängt; die Zeichenflächen des Tabellenzeilenobjekts werden als Zeichenelemente festgelegt, und die Tabellenzelle wird auf diesem Panel an den angegebenen Koordinaten gezeichnet. Der Bereich jeder Tabellenzelle wird im Tabellenzeilenobjekt (Punkt 5) durch eine Instanz der Klasse CBound festgelegt; an diese Instanz wird ein Objekt der Tabellenzellenklasse angehängt.
Dieser Algorithmus zum Erstellen von Tabellenzeilen und Tabellenzellen, bei dem jede Tabellenzeile in horizontale Bereiche unterteilt wird, an die Objekte der Tabellenzellenklasse angehängt werden, erleichtert das Sortieren und Neupositionieren von Tabellenzellen, indem diese einfach den gewünschten Bereichen der Tabellenzeile neu zugewiesen werden.
Aus dem oben Gesagten ergibt sich, dass wir eine neue Objektklasse benötigen, an die ein Zeiger auf das Steuerelement übergeben wird, auf dessen Zeichenfläche gezeichnet werden soll. Derzeit erstellen alle Bibliotheksobjekte beim Anlegen mit dem Operator new ihre eigenen Zeichenflächenobjekte für Hintergrund und Vordergrund. Wir möchten jedoch ein Objekt, dessen Größe sich festlegen und abrufen lässt und in dem sich zudem ein Zeiger auf das Steuerelement setzen lässt, auf dem gezeichnet werden soll.
Die Klasse CBound ermöglicht es, die Abmessungen des erstellten Objekts festzulegen und abzurufen, und ist Bestandteil des Basisobjekts aller Steuerelemente. In genau diesem Objekt werden die Zeichenflächen für Hintergrund und Vordergrund erstellt. Das bedeutet, dass ein weiteres Zwischenobjekt erstellt werden sollte, das vom Basisobjekt erbt und die Klasse CBound zum Festlegen und Abrufen der Abmessungen enthält. Die Klasse, in der CCanvas-Objekte erstellt werden, wird von diesem Objekt erben. Somit können wir von dieser Zwischenklasse die Klasse ableiten, an die ein Zeiger auf das Steuerelement übergeben wird, auf dem wir zeichnen werden.
Lassen Sie uns zunächst die Dateien der bereits erstellten Klassen fertigstellen und erst danach neue schreiben.
Bibliotheksklassen überarbeiten
Alle Dateien der in Entwicklung befindlichen Bibliothek befinden sich unter \MQL5\Indicators\Tables\Controls\. Sollten diese noch nicht verfügbar sein, finden Sie im vorherigen Artikel eine frühere Version aller Dateien. Für das Projekt wird außerdem die Datei der Tabellenklasse (die Modellkomponente) benötigt, die Sie dem Artikel entnehmen können, in dem wir die Entwicklung dieser Klasse abgeschlossen haben. Die Datei „Tables.mqh“ muss im Verzeichnis „\MQL5\Indicators\Tables\“ gespeichert werden. Die Dateien „Base.mqh“ und „Control.mqh“ werden überarbeitet.
Geben Sie ganz am Anfang der Datei „Tables.mqh“ im Makro-Abschnitt die Datei-ID an:
//+------------------------------------------------------------------+ //| Macros | //+------------------------------------------------------------------+ #define __TABLES__ // File ID #define MARKER_START_DATA -1 // Data start marker in a file #define MAX_STRING_LENGTH 128 // Maximum length of a string in a cell #define CELL_WIDTH_IN_CHARS 19 // Table cell width in characters
Dies ist erforderlich, damit die Makroersetzung MARKER_START_DATA in zwei verschiedenen Include-Dateien deklariert werden kann, sodass sich diese separat kompilieren lassen.
Öffnen Sie die Datei „Base.mqh“. Binden Sie die Klassendatei des Tabellenmodells darin ein und geben Sie die Vorwärtsdeklarationen der neuen Klassen an:
//+------------------------------------------------------------------+ //| Base.mqh | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" //+------------------------------------------------------------------+ //| Include libraries | //+------------------------------------------------------------------+ #include <Canvas\Canvas.mqh> // CCanvas class #include <Arrays\List.mqh> // CList class #include "..\Tables.mqh" //--- Forward declaration of control element classes class CBoundedObj; // Base class storing object dimensions class CCanvasBase; // Base class of graphical elements canvas class CCounter; // Delay counter class class CAutoRepeat; // Event auto-repeat class class CImagePainter; // Image drawing class class CVisualHint; // Hint class class CLabel; // Text label class class CButton; // Simple button class class CButtonTriggered; // Two-position 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 CTableRowView; // Class for visual representation of a table row class CPanel; // Panel control class class CGroupBox; // GroupBox control class class CContainer; // Container control class //+------------------------------------------------------------------+ //| Macro substitutions | //+------------------------------------------------------------------+
Umschließen Sie im Abschnitt für Makroersetzungen die Deklaration des Makros MARKER_START_DATA mit einer Prüfung, ob das Makro bereits existiert:
//+------------------------------------------------------------------+ //| Macro substitutions | //+------------------------------------------------------------------+ #define clrNULL 0x00FFFFFF // Transparent color for CCanvas #ifndef __TABLES__ #define MARKER_START_DATA -1 // Data start marker in a file #endif #define DEF_FONTNAME "Calibri" // Default font #define DEF_FONTSIZE 10 // Default font size #define DEF_EDGE_THICKNESS 3 // Zone width to capture the border/corner
Die Deklaration derselben Makroersetzung in zwei verschiedenen Dateien führt nun weder bei der separaten noch bei der gemeinsamen Kompilierung der beiden Dateien zu Kompilierungsfehlern.
Fügen Sie neue Typen zur Enumeration der Typen von UI-Elementen hinzu und legen Sie einen neuen maximalen Typ für das aktive Element fest:
//+------------------------------------------------------------------+ //| Enumerations | //+------------------------------------------------------------------+ enum ENUM_ELEMENT_TYPE // Enumeration of graphical element types { ELEMENT_TYPE_BASE = 0x10000, // Basic object of graphical elements ELEMENT_TYPE_COLOR, // Color object ELEMENT_TYPE_COLORS_ELEMENT, // Color object of the graphical object element ELEMENT_TYPE_RECTANGLE_AREA, // Rectangular area of the 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, // Basic object of graphical element sizes ELEMENT_TYPE_CANVAS_BASE, // Basic canvas object for graphical elements ELEMENT_TYPE_ELEMENT_BASE, // Basic object of graphical elements ELEMENT_TYPE_HINT, // Hint ELEMENT_TYPE_LABEL, // Text label ELEMENT_TYPE_BUTTON, // Simple button ELEMENT_TYPE_BUTTON_TRIGGERED, // Two-position 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 scroll bar slider ELEMENT_TYPE_SCROLLBAR_THUMB_V, // Vertical scroll bar slider ELEMENT_TYPE_SCROLLBAR_H, // ScrollBarHorisontal control ELEMENT_TYPE_SCROLLBAR_V, // ScrollBarVertical control ELEMENT_TYPE_TABLE_CELL, // Table cell (View) ELEMENT_TYPE_TABLE_ROW, // Table row (View) ELEMENT_TYPE_TABLE_COLUMN_CAPTION, // Table column header (View) ELEMENT_TYPE_TABLE_HEADER, // Table header (View) ELEMENT_TYPE_TABLE, // Table (View) ELEMENT_TYPE_PANEL, // Panel control ELEMENT_TYPE_GROUPBOX, // GroupBox control ELEMENT_TYPE_CONTAINER, // Container control }; #define ACTIVE_ELEMENT_MIN ELEMENT_TYPE_LABEL // Minimum value of the list of active elements #define ACTIVE_ELEMENT_MAX ELEMENT_TYPE_TABLE_HEADER // Maximum value of the list of active elements
Fügen Sie neue Rückgabewerte zur Funktion hinzu, die den Kurznamen des Elements anhand seines Typs zurückgibt:
//+------------------------------------------------------------------+ //| Return the short name of the element by type | //+------------------------------------------------------------------+ string ElementShortName(const ENUM_ELEMENT_TYPE type) { switch(type) { case ELEMENT_TYPE_ELEMENT_BASE : return "BASE"; // Basic object of graphical elements case ELEMENT_TYPE_HINT : return "HNT"; // Hint case ELEMENT_TYPE_LABEL : return "LBL"; // Text label case ELEMENT_TYPE_BUTTON : return "SBTN"; // Simple button case ELEMENT_TYPE_BUTTON_TRIGGERED : return "TBTN"; // Toggle 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 scroll bar slider case ELEMENT_TYPE_SCROLLBAR_THUMB_V : return "THMBV"; // Vertical scroll bar slider case ELEMENT_TYPE_SCROLLBAR_H : return "SCBH"; // ScrollBarHorisontal control case ELEMENT_TYPE_SCROLLBAR_V : return "SCBV"; // ScrollBarVertical control case ELEMENT_TYPE_TABLE_CELL : return "TCELL"; // Table cell (View) case ELEMENT_TYPE_TABLE_ROW : return "TROW"; // Table row (View) case ELEMENT_TYPE_TABLE_COLUMN_CAPTION : return "TCAPT"; // Table column header (View) case ELEMENT_TYPE_TABLE_HEADER : return "THDR"; // Table header (View) case ELEMENT_TYPE_TABLE : return "TABLE"; // Table (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 } }
Deklarieren Sie in der Basisklasse der UI-Elemente die Methode zum Setzen der Kennung als virtuelle Methode, da sie in den neuen Klassen überschrieben werden soll:
//+------------------------------------------------------------------+ //| Base class of graphical elements | //+------------------------------------------------------------------+ class CBaseObj : public CObject { protected: int m_id; // ID ushort m_name[]; // Name public: //--- Set (1) name and (2) ID void SetName(const string name) { ::StringToShortArray(name,this.m_name); } virtual void SetID(const int id) { this.m_id=id; } //--- Return (1) name and (2) ID string Name(void) const { return ::ShortArrayToString(this.m_name); } int ID(void) const { return this.m_id; } //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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_BASE); } //--- (1) Return and (2) display the object description in the journal virtual string Description(void); virtual void Print(void); //--- Constructor/destructor CBaseObj (void) : m_id(-1) { this.SetName(""); } ~CBaseObj (void) {} };
Jedes Objekt enthält ein Objekt der Klasse CBound für einen rechteckigen Bereich, das die Größe des Steuerelements zurückgibt. Außerdem verfügt jedes Steuerelement über eine Liste von CBound-Objekten. Mit dieser Liste können Sie zahlreiche CBound-Objekte speichern, mit denen Sie wiederum viele verschiedene Bereiche auf der Oberfläche des UI-Elements festlegen können.
Jeder dieser Bereiche kann für beliebige Szenarien genutzt werden. Sie können beispielsweise einen bestimmten Bereich innerhalb eines UI-Elements definieren, die Position des Mauszeigers innerhalb dieses Bereichs verfolgen und auf die Interaktion des Mauszeigers mit diesem Bereich reagieren. Ein bestimmtes Steuerelement kann innerhalb eines bestimmten Bereichs platziert werden, um es in diesem Bereich anzuzeigen. Dazu muss es möglich sein, einen Zeiger auf das Steuerelement im CBound-Objekt zu speichern.
Implementieren Sie eine solche Funktion in der Klasse „CBound“:
//+------------------------------------------------------------------+ //| Rectangular region class | //+------------------------------------------------------------------+ class CBound : public CBaseObj { protected: CBaseObj *m_assigned_obj; // Object assigned to the region CRect m_bound; // Rectangular area structure public: //--- Change the bounding rectangular (1) width, (2) height and (3) size void ResizeW(const int size) { this.m_bound.Width(size); } void ResizeH(const int size) { this.m_bound.Height(size); } void Resize(const int w,const int h) { this.m_bound.Width(w); this.m_bound.Height(h); } //--- Set (1) X, (2) Y and (3) both coordinates of the bounding rectangle void SetX(const int x) { this.m_bound.left=x; } void SetY(const int y) { this.m_bound.top=y; } void SetXY(const int x,const int y) { this.m_bound.LeftTop(x,y); } //--- (1) Set and (2) shift the bounding rectangle by the specified coordinates/offset size void Move(const int x,const int y) { this.m_bound.Move(x,y); } void Shift(const int dx,const int dy) { this.m_bound.Shift(dx,dy); } //--- Returns the object coordinates, dimensions, and boundaries int X(void) const { return this.m_bound.left; } int Y(void) const { return this.m_bound.top; } int Width(void) const { return this.m_bound.Width(); } int Height(void) const { return this.m_bound.Height(); } int Right(void) const { return this.m_bound.right-(this.m_bound.Width() >0 ? 1 : 0);} int Bottom(void) const { return this.m_bound.bottom-(this.m_bound.Height()>0 ? 1 : 0);} //--- Returns the flag indicating whether the cursor is inside the area bool Contains(const int x,const int y) const { return this.m_bound.Contains(x,y); } //--- (1) Assign and (2) return the pointer to the assigned element void AssignObject(CBaseObj *obj) { this.m_assigned_obj=obj; } CBaseObj *GetAssignedObj(void) { return this.m_assigned_obj; } //--- Return the object description virtual string Description(void); //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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_RECTANGLE_AREA); } //--- Constructors/destructor CBound(void) { ::ZeroMemory(this.m_bound); } CBound(const int x,const int y,const int w,const int h) { this.SetXY(x,y); this.Resize(w,h); } ~CBound(void) { ::ZeroMemory(this.m_bound); } };
Derzeit wird das Objekt für den rechteckigen Bereich vom Typ CBound in der Klasse CCanvasBase deklariert, in der zwei CCanvas-Objekte zum Zeichnen des Hintergrunds und des Vordergrunds eines UI-Elements erstellt werden. Das heißt, alle UI-Elemente enthalten zwei Zeichenflächen. Wir möchten jedoch eine Klasse erstellen, in der wir das Steuerelement angeben können, auf dessen Zeichenflächen wir zeichnen möchten. Dabei sollen weder eigene Zeichenflächen erstellt werden noch soll vom allgemeinen Konzept zur Erstellung grafischer Elemente abgewichen werden.
Das bedeutet, dass wir das Objekt der Klasse „CBound“ aus der Klasse „CCanvasBase“ in eine andere übergeordnete Klasse verlagern möchten, die keine Zeichenflächenobjekte erstellt und von der die Klasse „CCanvasBase“ erbt. In der Klasse „CCanvasBase“ sollen statt zweier Instanzen von „CCanvas“ Zeiger auf die zu erstellenden Zeichenflächen deklariert und eine Methode implementiert werden, die zwei Zeichenflächenobjekte erstellt. Außerdem möchten wir ein Flag deklarieren, das angibt, ob ein grafisches Element die Zeichenflächenobjekte für den Hintergrund und den Vordergrund verwaltet. Dies ist erforderlich, um das Löschen der erstellten Zeichenflächenobjekte zu verwalten.
Implementieren Sie in der Datei „Base.mqh“ unmittelbar nach der Klasse „CAutoRepeat“ und vor der Klasse „CCanvasBase“ eine neue Klasse „CBoundedObj“, die von „CBaseObj“ abgeleitet ist, und übertragen Sie einfach alle Methoden zur Arbeit mit dem „CBound“-Objekt aus der Klasse „CCanvasBase“ in diese Klasse:
//+------------------------------------------------------------------+ //| Base class storing object dimensions | //+------------------------------------------------------------------+ class CBoundedObj : public CBaseObj { protected: CBound m_bound; // Object boundaries bool m_canvas_owner; // Canvas ownership flag public: //--- Returns the object coordinates, dimensions, and boundaries int X(void) const { return this.m_bound.X(); } int Y(void) const { return this.m_bound.Y(); } int Width(void) const { return this.m_bound.Width(); } int Height(void) const { return this.m_bound.Height(); } int Right(void) const { return this.m_bound.Right(); } int Bottom(void) const { return this.m_bound.Bottom(); } //--- Change the bounding rectangular (1) width, (2) height and (3) size void BoundResizeW(const int size) { this.m_bound.ResizeW(size); } void BoundResizeH(const int size) { this.m_bound.ResizeH(size); } void BoundResize(const int w,const int h) { this.m_bound.Resize(w,h); } //--- Set (1) X, (2) Y and (3) both coordinates of the bounding rectangle void BoundSetX(const int x) { this.m_bound.SetX(x); } void BoundSetY(const int y) { this.m_bound.SetY(y); } void BoundSetXY(const int x,const int y) { this.m_bound.SetXY(x,y); } //--- (1) Set and (2) shift the bounding rectangle by the specified coordinates/offset size void BoundMove(const int x,const int y) { this.m_bound.Move(x,y); } void BoundShift(const int dx,const int dy) { this.m_bound.Shift(dx,dy); } //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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_BOUNDED_BASE); } CBoundedObj (void) : m_canvas_owner(true) {} CBoundedObj (const string user_name,const int id,const int x,const int y,const int w,const int h); ~CBoundedObj (void){} }; //+------------------------------------------------------------------+ //| CBoundedObj::Constructor | //+------------------------------------------------------------------+ CBoundedObj::CBoundedObj(const string user_name,const int id,const int x,const int y,const int w,const int h) : m_canvas_owner(true) { //--- Get the adjusted chart ID and the distance in pixels along the vertical Y axis this.m_bound.SetName(user_name); this.m_bound.SetID(id); this.m_bound.SetXY(x,y); this.m_bound.Resize(w,h); } //+------------------------------------------------------------------+ //| CBoundedObj::Save to file | //+------------------------------------------------------------------+ bool CBoundedObj::Save(const int file_handle) { //--- Save the parent object data if(!CBaseObj::Save(file_handle)) return false; //--- Save the canvas ownership flag if(::FileWriteInteger(file_handle,this.m_canvas_owner,INT_VALUE)!=INT_VALUE) return false; //--- Save the dimensions return this.m_bound.Save(file_handle); } //+------------------------------------------------------------------+ //| CBoundedObj::Load from file | //+------------------------------------------------------------------+ bool CBoundedObj::Load(const int file_handle) { //--- Load parent object data if(!CBaseObj::Load(file_handle)) return false; //--- Load the canvas ownership flag this.m_canvas_owner=::FileReadInteger(file_handle,INT_VALUE); //--- Load dimensions return this.m_bound.Load(file_handle); }
Die vorgestellte Klasse erbt lediglich die Eigenschaften der Basisklasse „CBaseObj“, ermöglicht die Festlegung von Objektgrenzen über die Klasse „CBound“ und verfügt über ein Zeichenflächenverwaltungsflag.
Die Basisklasse für die Zeichenflächen grafischer Elemente sollte nun von der neuen Klasse „CBoundedObj“ abgeleitet werden und nicht mehr, wie bisher, von der Klasse „CBaseObj“. Alles, was mit der Verwendung des Objekts der Klasse „CBound“ zum Festlegen und Zurückgeben der Abmessungen eines Elements zusammenhängt, wurde bereits in die neue Klasse „CBoundedObj“ verschoben und aus der Klasse „CCanvasBase“ entfernt. Nun werden Zeichenflächenobjekte nicht mehr als Instanzen einer Klasse deklariert, sondern als Zeiger auf die zu erstellenden CCanvas-Objekte:
//+------------------------------------------------------------------+ //| Base class of graphical elements canvas | //+------------------------------------------------------------------+ class CCanvasBase : public CBoundedObj { private: bool m_chart_mouse_wheel_flag; // Flag for sending mouse wheel scroll messages bool m_chart_mouse_move_flag; // Flag for sending mouse cursor movement messages bool m_chart_object_create_flag; // Flag for sending messages about the graphical object creation event bool m_chart_mouse_scroll_flag; // Flag for scrolling the chart with the left button and mouse wheel bool m_chart_context_menu_flag; // Flag of access to the context menu using the right click bool m_chart_crosshair_tool_flag; // Flag of access to the Crosshair tool using the middle click bool m_flags_state; // State of the flags for scrolling the chart with the wheel, the context menu, and the crosshair //--- Set chart restrictions (wheel scrolling, context menu, and crosshair) void SetFlags(const bool flag); protected: CCanvas *m_background; // Background canvas CCanvas *m_foreground; // Foreground canvas CCanvasBase *m_container; // Parent container object CColorElement m_color_background; // Background color control object CColorElement m_color_foreground; // Foreground color control object CColorElement m_color_border; // Border color control object
Methoden zum Abrufen der Koordinaten und Abmessungen grafischer Zeichenflächenobjekte sind öffentlich deklariert, und Methoden zum Ändern der Größe von Zeichenflächen sind als virtuelle Methoden implementiert:
//--- Return the graphical object coordinates, boundaries and dimensions public: int ObjectX(void) const { return this.m_obj_x; } int ObjectY(void) const { return this.m_obj_y; } int ObjectWidth(void) const { return this.m_background.Width(); } int ObjectHeight(void) const { return this.m_background.Height(); } int ObjectRight(void) const { return this.ObjectX()+this.ObjectWidth()-1; } int ObjectBottom(void) const { return this.ObjectY()+this.ObjectHeight()-1; } //--- Change the graphical object (1) width, (2) height and (3) size protected: virtual bool ObjectResizeW(const int size); virtual bool ObjectResizeH(const int size); bool ObjectResize(const int w,const int h); //--- Set the graphical object (1) X, (2) Y and (3) both coordinates virtual bool ObjectSetX(const int x); virtual bool ObjectSetY(const int y); bool ObjectSetXY(const int x,const int y) { return(this.ObjectSetX(x) && this.ObjectSetY(y)); }
Im geschützten Bereich der Klasse wird eine Methode zum Erstellen von Zeichenflächen deklariert.:
//--- Set the pointer to the parent container object void SetContainerObj(CCanvasBase *obj); protected: //--- Create background and foreground canvases bool CreateCanvasObjects(void); //--- Create OBJ_BITMAP_LABEL bool Create(const long chart_id,const int wnd,const string object_name,const int x,const int y,const int w,const int h); public: //--- (1) Set and (2) return the state void SetState(ENUM_ELEMENT_STATE state) { this.m_state=state; this.ColorsToDefault(); } ENUM_ELEMENT_STATE State(void) const { return this.m_state; }
Die Methode, die ein Flag setzt, um die Beschneidung eines Elements an den Containergrenzen zuzulassen, ist als virtuelle Methode implementiert:
//--- Set (1) movability, (2) main object flag for the object and (3) resizability //--- cropping along the container borders void SetMovable(const bool flag) { this.m_movable=flag; } void SetAsMain(void) { this.m_main=true; } virtual void SetResizable(const bool flag) { this.m_resizable=flag; } void SetAutorepeat(const bool flag) { this.m_autorepeat_flag=flag; } void SetScrollable(const bool flag) { this.m_scroll_flag=flag; } virtual void SetTrimmered(const bool flag) { this.m_trim_flag=flag; }
Im Klassenkonstruktor wird nun eine Methode zum Erstellen von Zeichenflächenobjekten für den Hintergrund und den Vordergrund aufgerufen:
//+------------------------------------------------------------------+ //| CCanvasBase::Constructor | //+------------------------------------------------------------------+ CCanvasBase::CCanvasBase(const string object_name,const long chart_id,const int wnd,const int x,const int y,const int w,const int h) : m_program_name(::MQLInfoString(MQL_PROGRAM_NAME)), m_wnd(wnd<0 ? 0 : wnd), m_alpha_bg(0), m_alpha_fg(255), m_hidden(false), m_blocked(false), m_focused(false), m_movable(false), m_resizable(false), m_main(false), m_autorepeat_flag(false), m_trim_flag(true), m_scroll_flag(false), m_border_width_lt(0), m_border_width_rt(0), m_border_width_up(0), m_border_width_dn(0), m_z_order(0), m_state(0), m_cursor_delta_x(0), m_cursor_delta_y(0) { //--- Get the adjusted chart ID and the distance in pixels along the vertical Y axis //--- between the upper frame of the indicator subwindow and the upper frame of the chart main window this.m_chart_id=this.CorrectChartID(chart_id); //--- If failed to create canvases, leave if(!this.CreateCanvasObjects()) return; //--- If the graphical resource and graphical object are created if(this.Create(this.m_chart_id,this.m_wnd,object_name,x,y,w,h)) { //--- Clear the background and foreground canvases and set the initial coordinate values, //--- names of graphic objects and properties of text drawn in the foreground this.Clear(false); this.m_obj_x=x; this.m_obj_y=y; this.m_color_background.SetName("Background"); this.m_color_foreground.SetName("Foreground"); this.m_color_border.SetName("Border"); this.m_foreground.FontSet(DEF_FONTNAME,-DEF_FONTSIZE*10,FW_MEDIUM); this.m_bound.SetName("Perimeter"); //--- Remember permissions for the mouse and chart tools this.Init(); } }
Eine Methode, die Zeichenflächen für den Hintergrund und den Vordergrund erstellt:
//+------------------------------------------------------------------+ //| CCanvasBase::Create background and foreground canvases | //+------------------------------------------------------------------+ bool CCanvasBase::CreateCanvasObjects(void) { //--- If both canvases have already been created, or the class does not manage canvases, return 'true' if((this.m_background!=NULL && this.m_foreground!=NULL) || !this.m_canvas_owner) return true; //--- Create the background canvas this.m_background=new CCanvas(); if(this.m_background==NULL) { ::PrintFormat("%s: Error! Failed to create background canvas",__FUNCTION__); return false; } //--- Create the foreground canvas this.m_foreground=new CCanvas(); if(this.m_foreground==NULL) { ::PrintFormat("%s: Error! Failed to create foreground canvas",__FUNCTION__); return false; } //--- All is successful return true; }
In der Methode, die das Objekt zerstört, prüfen Sie nun das Zeichenflächenverwaltungsflag:
//+------------------------------------------------------------------+ //| CCanvasBase::Destroy the object | //+------------------------------------------------------------------+ void CCanvasBase::Destroy(void) { if(this.m_canvas_owner) { this.m_background.Destroy(); this.m_foreground.Destroy(); delete this.m_background; delete this.m_foreground; this.m_background=NULL; this.m_foreground=NULL; } }
Zeichenflächen werden nur gelöscht, wenn das Objekt sie verwaltet. Wenn einem Objekt die Zeichenflächen eines anderen Steuerelements zum Zeichnen übergeben werden, löscht es diese nicht – sie sollten ausschließlich von dem Objekt gelöscht werden, dem sie gehören.
In der Methode zur Standardinitialisierung der Klasse wird für das Objekt ein Zeichenflächenverwaltungsflag gesetzt:
//+------------------------------------------------------------------+ //| CCanvasBase::Class initialization | //+------------------------------------------------------------------+ void CCanvasBase::Init(void) { //--- Remember permissions for the mouse and chart tools this.m_chart_mouse_wheel_flag = ::ChartGetInteger(this.m_chart_id, CHART_EVENT_MOUSE_WHEEL); this.m_chart_mouse_move_flag = ::ChartGetInteger(this.m_chart_id, CHART_EVENT_MOUSE_MOVE); this.m_chart_object_create_flag = ::ChartGetInteger(this.m_chart_id, CHART_EVENT_OBJECT_CREATE); this.m_chart_mouse_scroll_flag = ::ChartGetInteger(this.m_chart_id, CHART_MOUSE_SCROLL); this.m_chart_context_menu_flag = ::ChartGetInteger(this.m_chart_id, CHART_CONTEXT_MENU); this.m_chart_crosshair_tool_flag= ::ChartGetInteger(this.m_chart_id, CHART_CROSSHAIR_TOOL); //--- Set permissions for the mouse and chart ::ChartSetInteger(this.m_chart_id, CHART_EVENT_MOUSE_WHEEL, true); ::ChartSetInteger(this.m_chart_id, CHART_EVENT_MOUSE_MOVE, true); ::ChartSetInteger(this.m_chart_id, CHART_EVENT_OBJECT_CREATE, true); //--- Initialize the object default colors this.InitColors(); //--- Initialize the millisecond timer ::EventSetMillisecondTimer(16); //--- Canvas ownership flag this.m_canvas_owner=true; }
Nur bei Objekten, die keine eigenen Zeichenflächen haben und von der Klasse CBoundedObj erben, muss dieses Flag auf false zurückgesetzt werden.
Öffnen Sie nun die Datei „Controls.mqh“ und nehmen Sie Verbesserungen vor.
Fügen Sie im Abschnitt für Makroersetzungen zwei neue Makroersetzungen hinzu, die die Standardhöhe der Tabellenzeile und des Tabellenkopfs festlegen:
//+------------------------------------------------------------------+ //| Macro substitutions | //+------------------------------------------------------------------+ #define DEF_LABEL_W 50 // Text label default width #define DEF_LABEL_H 16 // Text label default 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_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 slider #define DEF_AUTOREPEAT_DELAY 500 // Delay before launching auto-repeat #define DEF_AUTOREPEAT_INTERVAL 100 // Auto-repeat frequency
Die Datei enthält eine Klasse für eine verkettete Liste von CListObj-Objekten, in der grafische Elemente gespeichert werden. Wir haben diese Klasse aus der Datei der Tabellenmodellklasse in diese Datei kopiert. Wenn Sie den Namen der Klasse unverändert lassen, kommt es zu einem Namenskonflikt, und die Objekte, die in diesen beiden Listen in verschiedenen Dateien gespeichert sind, sind völlig unterschiedlich. Lassen Sie die Klasse also unverändert, benennen Sie sie aber um. Dies wird eine Klasse für eine verkettete Liste von UI-Elementen sein:
//+------------------------------------------------------------------+ //| Class of the linked list of graphical elements | //+------------------------------------------------------------------+ class CListElm : public CList { protected: ENUM_ELEMENT_TYPE m_element_type; // Created object type in CreateElement() public: //--- Set the element type void SetElementType(const ENUM_ELEMENT_TYPE type) { this.m_element_type=type; } //--- Virtual method (1) for loading a list from a file, (2) for creating a list element virtual bool Load(const int file_handle); virtual CObject *CreateElement(void); };
Ersetzen Sie in der gesamten Datei die Zeichenfolge „CListObj“ durch die Zeichenfolge „CListElm“.
Fügen Sie in der Methode zum Erstellen eines Listenelements neue Typen von UI-Elementen hinzu:
//+------------------------------------------------------------------+ //| List element creation method | //+------------------------------------------------------------------+ CObject *CListElm::CreateElement(void) { //--- Create a new object depending on the object type in m_element_type switch(this.m_element_type) { case ELEMENT_TYPE_BASE : return new CBaseObj(); // Basic object of graphical elements case ELEMENT_TYPE_COLOR : return new CColor(); // Color object case ELEMENT_TYPE_COLORS_ELEMENT : return new CColorElement(); // Color object of the graphical object element case ELEMENT_TYPE_RECTANGLE_AREA : return new CBound(); // Rectangular area of the element case ELEMENT_TYPE_IMAGE_PAINTER : return new CImagePainter(); // Object for drawing images case ELEMENT_TYPE_CANVAS_BASE : return new CCanvasBase(); // Basic object of graphical elements case ELEMENT_TYPE_ELEMENT_BASE : return new CElementBase(); // Basic object of graphical elements case ELEMENT_TYPE_HINT : return new CVisualHint(); // Hint 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(); // Toggle 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 : return new CTableCellView(); // Table cell (View) case ELEMENT_TYPE_TABLE_ROW : return new CTableRowView(); // Table row (View) case ELEMENT_TYPE_TABLE_COLUMN_CAPTION : return new CColumnCaptionView(); // Table column header (View) case ELEMENT_TYPE_TABLE_HEADER : return new CTableHeaderView(); // Table header (View) case ELEMENT_TYPE_TABLE : 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; } }
Fügen Sie in der Basisklasse für UI-Elemente eine Methode hinzu, die einen Zeiger auf das Objekt zurückgibt:
public: //--- Return itself CElementBase *GetObject(void) { return &this; } //--- Return the pointer to (1) the drawing class and (2) the list of hints CImagePainter *Painter(void) { return &this.m_painter; } CListElm *GetListHints(void) { return &this.m_list_hints; }
Deklarieren Sie in der Klasse für Textbeschriftungen die Methode, die den Text auf der Zeichenfläche anzeigt, als virtuell:
//--- Set the text (1) X and (2) Y coordinate void SetTextShiftH(const int x) { this.ClearText(); this.m_text_x=x; } void SetTextShiftV(const int y) { this.ClearText(); this.m_text_y=y; } //--- Display the text virtual void DrawText(const int dx, const int dy, const string text, const bool chart_redraw); //--- Draw the appearance virtual void Draw(const bool chart_redraw);
Überarbeiten Sie in der Panel-Klasse CPanel die Methoden zur Größenanpassung:
//+------------------------------------------------------------------+ //| CPanel::Change the object width | //+------------------------------------------------------------------+ bool CPanel::ResizeW(const int w) { if(!this.ObjectResizeW(w)) return false; this.BoundResizeW(w); this.SetImageSize(w,this.Height()); if(!this.ObjectTrim()) { this.Update(false); this.Draw(false); } //--- Get the pointer to the base element and, if it exists, its type is container, //--- check the ratio of the current element dimensions to the container dimensions //--- to display scrollbars in the container if necessary CContainer *base=this.GetContainer(); if(base!=NULL && base.Type()==ELEMENT_TYPE_CONTAINER) base.CheckElementSizes(&this); //--- In the loop through the attached elements, trim each element along the container boundaries int total=this.m_list_elm.Total(); for(int i=0;i<total;i++) { CElementBase *elm=this.GetAttachedElementAt(i); if(elm!=NULL) elm.ObjectTrim(); } //--- All is successful return true; } //+------------------------------------------------------------------+ //| CPanel::Change the object height | //+------------------------------------------------------------------+ bool CPanel::ResizeH(const int h) { if(!this.ObjectResizeH(h)) return false; this.BoundResizeH(h); this.SetImageSize(this.Width(),h); if(!this.ObjectTrim()) { this.Update(false); this.Draw(false); } //--- Get the pointer to the base element and, if it exists, its type is container, //--- check the ratio of the current element dimensions to the container dimensions //--- to display scrollbars in the container if necessary CContainer *base=this.GetContainer(); if(base!=NULL && base.Type()==ELEMENT_TYPE_CONTAINER) base.CheckElementSizes(&this); //--- In the loop through the attached elements, trim each element along the container boundaries int total=this.m_list_elm.Total(); for(int i=0;i<total;i++) { CElementBase *elm=this.GetAttachedElementAt(i); if(elm!=NULL) elm.ObjectTrim(); } //--- All is successful return true; } //+------------------------------------------------------------------+ //| CPanel::Change the object size | //+------------------------------------------------------------------+ bool CPanel::Resize(const int w,const int h) { if(!this.ObjectResize(w,h)) return false; this.BoundResize(w,h); this.SetImageSize(w,h); if(!this.ObjectTrim()) { this.Update(false); this.Draw(false); } //--- Get the pointer to the base element and, if it exists, its type is container, //--- check the ratio of the current element dimensions to the container dimensions //--- to display scrollbars in the container if necessary CContainer *base=this.GetContainer(); if(base!=NULL && base.Type()==ELEMENT_TYPE_CONTAINER) base.CheckElementSizes(&this); //--- In the loop through the attached elements, trim each element along the container boundaries int total=this.m_list_elm.Total(); for(int i=0;i<total;i++) { CElementBase *elm=this.GetAttachedElementAt(i); if(elm!=NULL) elm.ObjectTrim(); } //--- All is successful return true; }
Im Kern besteht die Überarbeitung der Methoden darin, die neuen Abmessungen eines Elements anhand der Containergrenzen zu prüfen, wenn sich das Element in einem Container befindet oder seine Größe geändert wurde. Wenn ein Element über die Grenzen des Containers hinausgewachsen ist, wird es entsprechend der Containergröße beschnitten (dies ist bereits implementiert); zusätzlich sollten jedoch Bildlaufleisten am Container erscheinen. Wir haben diese Prüfung mithilfe der Methode CheckElementSizes() des Container-Objekts in die Methoden zur Größenanpassung von UI-Elementen integriert.
Zeichnen Sie in der Methode zum Zeichnen des Erscheinungsbilds eines Panel-Objekts in der Klasse CPanel einen Rahmen nur dann, wenn der Parameter BorderWidth für mindestens eine der vier Seiten einen Wert ungleich null hat:
//+------------------------------------------------------------------+ //| CPanel::Draw the appearance | //+------------------------------------------------------------------+ void CPanel::Draw(const bool chart_redraw) { //--- Fill the object with background color this.Fill(this.BackColor(),false); //--- 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); //--- Set the color for the dark and light lines and draw the panel frame color clr_dark =(this.BackColor()==clrNULL ? this.BackColor() : this.GetBackColorControl().NewColor(this.BackColor(),-20,-20,-20)); color clr_light=(this.BackColor()==clrNULL ? this.BackColor() : this.GetBackColorControl().NewColor(this.BackColor(), 6, 6, 6)); if(this.BorderWidthBottom()+this.BorderWidthLeft()+this.BorderWidthRight()+this.BorderWidthTop()!=0) this.m_painter.FrameGroupElements(this.AdjX(this.m_painter.X()),this.AdjY(this.m_painter.Y()), this.m_painter.Width(),this.m_painter.Height(),this.Text(), this.ForeColor(),clr_dark,clr_light,this.AlphaFG(),true); //--- Update the background canvas without redrawing the chart this.m_background.Update(false); //--- Draw the list elements for(int i=0;i<this.m_list_elm.Total();i++) { CElementBase *elm=this.GetAttachedElementAt(i); if(elm!=NULL && elm.Type()!=ELEMENT_TYPE_SCROLLBAR_H && elm.Type()!=ELEMENT_TYPE_SCROLLBAR_V) elm.Draw(false); } //--- If specified, update the chart if(chart_redraw) ::ChartRedraw(this.m_chart_id); }
Ergänzen Sie in der Panel-Objektklasse die Methode zum Erstellen und Hinzufügen eines neuen Elements zur Liste um die Erstellung neuer Steuerelemente:
//+------------------------------------------------------------------+ //| CPanel::Create and add 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 graphical object name int elm_total=this.m_list_elm.Total(); string obj_name=this.NameFG()+"_"+ElementShortName(type)+(string)elm_total; //--- Calculate the coordinates int x=this.X()+dx; int y=this.Y()+dy; //--- Create a new object depending on the object type 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; // Toggle 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; // 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; // 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 : element = new CTableRowView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h); break; // Table row visual representation object case ELEMENT_TYPE_TABLE_COLUMN_CAPTION : element = new CColumnCaptionView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h); break; // Table column header visual representation object case ELEMENT_TYPE_TABLE_HEADER : element = new CTableHeaderView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h); break; // Table header visual representation object case ELEMENT_TYPE_TABLE : element = new CTableView(obj_name,text,this.m_chart_id,this.m_wnd,x,y,w,h); break; // Table visual representation object 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 is not 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 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 is not added to the list, report this, remove 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 the children ones are attached to CElementBase *elm=this.GetContainer(); //--- If the parent element is of 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 the pointer to the horizontal scrollbar and move 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 the pointer to the vertical scrollbar and move it to the front CScrollBarV *sbv=container_obj.GetScrollBarV(); if(sbv!=NULL) sbv.BringToTop(false); } } //--- Return the pointer to the created and attached element return element; }
Ergänzen Sie die Methode, die ein Objekt in den Vordergrund setzt, um die Beschneidung angehängter Objekte entsprechend der Containergröße:
//+------------------------------------------------------------------+ //| CPanel::Bring an object to the foreground | //+------------------------------------------------------------------+ void CPanel::BringToTop(const bool chart_redraw) { //--- Bring the panel to the foreground CCanvasBase::BringToTop(false); //--- Bring attached objects to the foreground for(int i=0;i<this.m_list_elm.Total();i++) { CElementBase *elm=this.GetAttachedElementAt(i); if(elm!=NULL) { if(elm.Type()==ELEMENT_TYPE_SCROLLBAR_H || elm.Type()==ELEMENT_TYPE_SCROLLBAR_V) continue; elm.BringToTop(false); elm.ObjectTrim(); } } //--- If specified, redraw the chart if(chart_redraw) ::ChartRedraw(this.m_chart_id); }
In der Klasse der horizontalen Bildlaufleiste gibt es ein Flag, das angibt, dass das Element an den Containergrenzen beschnitten werden kann. Das Bildlaufleistenobjekt besteht aus mehreren Objekten, und für jedes dieser Objekte sollte derselbe Flag-Wert gesetzt werden. Lassen Sie uns alles in einer einzigen Methode erledigen. Überschreiben Sie in der Klasse die Methode, die das Beschneidungsflag für die Containergrenzen setzt:
//+------------------------------------------------------------------+ //| Horizontal scrollbar class | //+------------------------------------------------------------------+ class CScrollBarH : public CPanel { protected: CButtonArrowLeft *m_butt_left; // Left arrow button CButtonArrowRight*m_butt_right; // Right arrow button CScrollBarThumbH *m_thumb; // Scrollbar slider public: //--- Return the pointer to the (1) left, (2) right button and (3) slider CButtonArrowLeft *GetButtonLeft(void) { return this.m_butt_left; } CButtonArrowRight*GetButtonRight(void) { return this.m_butt_right; } CScrollBarThumbH *GetThumb(void) { return this.m_thumb; } //--- (1) Sets and (2) return the chart update flag void SetChartRedrawFlag(const bool flag) { if(this.m_thumb!=NULL) this.m_thumb.SetChartRedrawFlag(flag); } bool ChartRedrawFlag(void) const { return(this.m_thumb!=NULL ? this.m_thumb.ChartRedrawFlag() : false); } //--- Return (1) the track length (2) start and (3) the slider position int TrackLength(void) const; int TrackBegin(void) const; int ThumbPosition(void) const; //--- Set the slider position bool SetThumbPosition(const int pos) const { return(this.m_thumb!=NULL ? this.m_thumb.MoveX(pos) : false); } //--- Change the slider size bool SetThumbSize(const uint size) const { return(this.m_thumb!=NULL ? this.m_thumb.ResizeW(size) : false); } //--- Change the object width virtual bool ResizeW(const int size); //--- Set the flag of visibility in the container virtual void SetVisibleInContainer(const bool flag); //--- Set the clipping flag to the container borders virtual void SetTrimmered(const bool flag); //--- Draw the appearance virtual void Draw(const bool chart_redraw); //--- Object type virtual int Type(void) const { return(ELEMENT_TYPE_SCROLLBAR_H); } //--- Initialize (1) the class object and (2) default object colors void Init(void); virtual void InitColors(void); //--- Wheel scroll handler (Wheel) virtual void OnWheelEvent(const int id, const long lparam, const double dparam, const string sparam); //--- Constructors/destructor CScrollBarH(void); CScrollBarH(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); ~CScrollBarH(void) {} };
Implementierung der Methode:
//+------------------------------------------------------------------+ //| CScrollBarH::Set the clipping flag to the container borders | //+------------------------------------------------------------------+ void CScrollBarH::SetTrimmered(const bool flag) { this.m_trim_flag=flag; if(this.m_butt_left!=NULL) this.m_butt_left.SetTrimmered(flag); if(this.m_butt_right!=NULL) this.m_butt_right.SetTrimmered(flag); if(this.m_thumb!=NULL) this.m_thumb.SetTrimmered(flag); }
Für jedes der Objekte, aus denen sich die Bildlaufleiste zusammensetzt, wird ein an die Methode übergebenes Flag gesetzt.
In der Objektinitialisierungsmethode müssen Sie das Beschneidungsflag für die Containergrenzen nicht mehr für jedes einzelne Element setzen. Es reicht aus, die Methode SetTrimmered() am Ende der Methode aufzurufen:
//+------------------------------------------------------------------+ //| CScrollBarH::Initialization | //+------------------------------------------------------------------+ void CScrollBarH::Init(void) { //--- Initialize a parent class CPanel::Init(); //--- background - opaque this.SetAlphaBG(255); //--- Frame width and text this.SetBorderWidth(0); this.SetText(""); //--- Create scroll buttons int w=this.Height(); int h=this.Height(); this.m_butt_left = this.InsertNewElement(ELEMENT_TYPE_BUTTON_ARROW_LEFT, "","ButtL",0,0,w,h); this.m_butt_right= this.InsertNewElement(ELEMENT_TYPE_BUTTON_ARROW_RIGHT,"","ButtR",this.Width()-w,0,w,h); if(this.m_butt_left==NULL || this.m_butt_right==NULL) { ::PrintFormat("%s: Init failed",__FUNCTION__); return; } //--- Customize the colors and appearance of the left arrow button this.m_butt_left.SetImageBound(1,1,w-2,h-4); this.m_butt_left.InitBackColors(this.m_butt_left.BackColorFocused()); this.m_butt_left.ColorsToDefault(); this.m_butt_left.InitBorderColors(this.BorderColor(),this.m_butt_left.BackColorFocused(),this.m_butt_left.BackColorPressed(),this.m_butt_left.BackColorBlocked()); this.m_butt_left.ColorsToDefault(); //--- Customize the colors and appearance of the right arrow button this.m_butt_right.SetImageBound(1,1,w-2,h-4); this.m_butt_right.InitBackColors(this.m_butt_right.BackColorFocused()); this.m_butt_right.ColorsToDefault(); this.m_butt_right.InitBorderColors(this.BorderColor(),this.m_butt_right.BackColorFocused(),this.m_butt_right.BackColorPressed(),this.m_butt_right.BackColorBlocked()); this.m_butt_right.ColorsToDefault(); //--- Create a slider int tsz=this.Width()-w*2; this.m_thumb=this.InsertNewElement(ELEMENT_TYPE_SCROLLBAR_THUMB_H,"","ThumbH",w,1,tsz-w*4,h-2); if(this.m_thumb==NULL) { ::PrintFormat("%s: Init failed",__FUNCTION__); return; } //--- Set the slider colors and set its movability flag this.m_thumb.InitBackColors(this.m_thumb.BackColorFocused()); this.m_thumb.ColorsToDefault(); this.m_thumb.InitBorderColors(this.m_thumb.BackColor(),this.m_thumb.BackColorFocused(),this.m_thumb.BackColorPressed(),this.m_thumb.BackColorBlocked()); this.m_thumb.ColorsToDefault(); this.m_thumb.SetMovable(true); //--- Prohibit independent chart redrawing this.m_thumb.SetChartRedrawFlag(false); //--- Initially not displayed in the container and not clipped to its borders this.SetVisibleInContainer(false); this.SetTrimmered(false); }
Genau dieselben Verbesserungen wurden auch für die Klasse der vertikalen Bildlaufleiste vorgenommen. Sie sind mit den bereits besprochenen Verbesserungen identisch und werden daher hier nicht erneut erläutert.
Machen Sie die Methode CheckElementSizes in der Klasse des Containerobjekts öffentlich:
//+------------------------------------------------------------------+ //| Container class | //+------------------------------------------------------------------+ class CContainer : public CPanel { private: bool m_visible_scrollbar_h; // Visibility flag for the horizontal scrollbar bool m_visible_scrollbar_v; // Vertical scrollbar visibility flag int m_init_border_size_top; // Initial border size from the top int m_init_border_size_bottom; // Initial border size from the bottom int m_init_border_size_left; // Initial border size from the left int m_init_border_size_right; // Initial border size from the right //--- Return the type of the element that sent the event ENUM_ELEMENT_TYPE GetEventElementType(const string name); protected: CScrollBarH *m_scrollbar_h; // Pointer to the horizontal scrollbar CScrollBarV *m_scrollbar_v; // Pointer to the vertical scrollbar //--- Handler for dragging element edges and corners virtual void ResizeActionDragHandler(const int x, const int y); public: //--- Check the dimensions of the element to display scrollbars void CheckElementSizes(CElementBase *element); protected: //--- Calculate and return the size (1) of the slider, (2) the full size, (3) the working size of the horizontal scrollbar track int ThumbSizeHorz(void); int TrackLengthHorz(void) const { return(this.m_scrollbar_h!=NULL ? this.m_scrollbar_h.TrackLength() : 0); } int TrackEffectiveLengthHorz(void) { return(this.TrackLengthHorz()-this.ThumbSizeHorz()); }
Diese Methode wird von den an den Container gebundenen Elementen aufgerufen und muss öffentlich sein, damit darauf zugegriffen werden kann.
Wir haben uns die wichtigsten Verbesserungen an den Bibliotheksklassen angesehen. Einige kleinere Verbesserungen und Fehlerbehebungen wurden hier nicht behandelt. Den vollständigen Code finden Sie in den dem Artikel beigefügten Dateien.
Das Tabellenmodell besteht aus einer Tabellenzelle, einer Tabellenzeile und einer Liste von Tabellenzeilen, die zusammen eine Tabelle bilden. Darüber hinaus hat die Tabelle einen Tabellenkopf, der aus den Spaltenüberschriften der Tabelle besteht.
- Eine Tabellenzelle ist ein eigenständiges Element, das die Zeilennummer, die Spaltennummer und den Inhalt speichert;
- Eine Tabellenzeile hat eine eigene Nummer und besteht aus einer Liste von Tabellenzellen;
- Eine Tabelle ist eine Liste von Tabellenzeilen und kann einen Tabellenkopf haben, der eine Liste von Spaltenüberschriften darstellt.
Die Ansichtskomponente wird zur Darstellung der Daten aus dem Tabellenmodell in etwa denselben Aufbau aufweisen. Das Tabellenobjekt wird beispielsweise auf einem Datenarray und einem Array mit den Überschriften dieser Daten basieren. Anschließend übergeben wir einen Zeiger auf das Tabellenmodell (die Modellkomponente) an das erstellte Objekt zur visuellen Darstellung der Tabelle (die Ansichtskomponente), woraufhin alle Daten in die Tabellenzellen geschrieben werden.
In diesem Entwicklungsschritt wird eine einfache statische Tabelle erstellt, deren Darstellung noch nicht mit dem Mauszeiger gesteuert werden kann.
Tabellenzellenklasse (Ansicht)
Die Tabelle besteht aus einer Liste von Tabellenzeilen. Die Tabellenzeilen bestehen wiederum aus Objekten, die über zwei Zeichenflächen zum Zeichnen des Hintergrunds und des Vordergrunds verfügen. Tabellenzellen sind horizontal in ihren Tabellenzeilen angeordnet. Es ist nicht sinnvoll, Zellen eigene Zeichenflächen zuzuweisen. Sie können jede Tabellenzeile einfach in Bereiche „aufteilen“, wobei jeder Bereich der Position der jeweiligen Zelle entspricht. Anschließend zeichnen Sie die Zelldaten auf die Zeichenfläche des Tabellenzeilenobjekts.
Genau zu diesem Zweck haben wir gleich zu Beginn eine Zwischenklasse erstellt. Sie enthält lediglich die Größe und die Koordinaten des Objekts sowie einen Zeiger auf das Steuerelement, auf dessen Zeichenfläche gezeichnet wird. Ein solches Objekt wird dann eine Tabellenzelle sein. Wir übergeben einen Zeiger auf das Tabellenzeilenobjekt, um auf dessen Zeichenflächen zu zeichnen.
Implementieren Sie eine neue Klasse in „Controls.mqh“:
//+------------------------------------------------------------------+ //| 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 cell) int m_text_x; // Text X coordinate (offset relative to the left border of the object area) int m_text_y; // Y text coordinate (offset relative to the top border of the object area) ushort m_text[]; // Text //--- Return the offsets of the initial drawing coordinates on the canvas relative to the canvas and the coordinates of the base element 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 offset of the canvas 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 anchor point bool GetTextCoordsByAnchor(int &x, int&y); public: //--- (1) Set and (2) return the cell text void SetText(const string text) { ::StringToShortArray(text,this.m_text); } string Text(void) const { return ::ShortArrayToString(this.m_text); } //--- Set the ID virtual void SetID(const int id) { this.m_index=this.m_id=id; } //--- (1) Set and (2) return the cell index void SetIndex(const int index) { this.SetID(index); } int Index(void) const { return this.m_index; } //--- (1) Set and (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 and (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 and (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; } //--- Sets the 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 and (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 in the journal void TableCellModelPrint(void); //--- (1) Fill the object with the background color, (2) update the object to reflect the changes and (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 the text virtual void DrawText(const int dx, const int dy, const string text, const bool chart_redraw); //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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); } //--- Initialize a class object void Init(const string text); //--- Return the object description 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){} };
Alle Variablen und Methoden sind hier im Code mit Kommentaren versehen. Der Index der Zelle und ihre Kennung sind hier ein und dasselbe. Daher wurde die virtuelle Methode SetID() überschrieben, sodass Index und Kennung auf denselben Wert gesetzt werden. Schauen wir uns die Implementierung der deklarierten Methoden an.
In den Klassenkonstruktoren wird die Methode zur Objektinitialisierung aufgerufen, wobei die Zellenkennung und der Name der Zelle festgelegt werden:
//+------------------------------------------------------------------------+ //| CTableCellView::Default constructor. Builds an object in the main | //| window of the current chart at coordinates 0,0 with default dimensions | //+------------------------------------------------------------------------+ CTableCellView::CTableCellView(void) : CBoundedObj("TableCell",-1,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H), m_index(-1),m_text_anchor(ANCHOR_LEFT) { //--- Initialization this.Init(""); this.SetID(-1); this.SetName("TableCell"); } //+-------------------------------------------------------------------------------+ //| CTableCellView::Parametric constructor. Builds an object | //| in the specified window of the specified chart with the specified text, | //| coordinates and dimensions | //+-------------------------------------------------------------------------------+ CTableCellView::CTableCellView(const int id, const string user_name, const string text, const int x, const int y, const int w, const int h) : CBoundedObj(user_name,id,x,y,w,h), m_index(-1),m_text_anchor(ANCHOR_LEFT) { //--- Initialization this.Init(text); this.SetID(id); this.SetName(user_name); }
Initialisierungsmethode für Klassenobjekte:
//+------------------------------------------------------------------+ //| CTableCellView::Initialization | //+------------------------------------------------------------------+ void CTableCellView::Init(const string text) { //--- The class does not manage canvases this.m_canvas_owner=false; //--- Cell text this.SetText(text); //--- Default text offsets this.m_text_x=2; this.m_text_y=0; }
Setzen Sie für das Objekt unbedingt ein Flag, das angibt, dass es keine Zeichenflächen verwaltet, damit beim Zerstören des Objekts keine Zeichenflächen anderer Objekte gelöscht werden.
Eine Methode, die eine Beschreibung des Objekts zurückgibt:
//+------------------------------------------------------------------+ //| CTableCellView::Return the object description | //+------------------------------------------------------------------+ string CTableCellView::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()); }
Die Methode gibt eine Zeile mit dem Namen des Objekttyps, der Kennung, den Koordinaten und den Zellengrößen in das Protokoll aus.
Eine Methode, mit der einer Zelle eine Tabellenzeile sowie eine Hintergrund- und eine Vordergrundzeichenfläche zugewiesen werden:
//+---------------------------------------------------------------------+ //| CTableCellView::Assigns the row, 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(); }
Ein Zeiger auf ein Tabellenzeilenobjekt wird an die Methode übergeben (die Klassenbeschreibung folgt weiter unten); ist der Zeiger ungültig, wird dies gemeldet und NULL zurückgegeben. Anschließend wird ein Zeiger auf eine Tabellenzeile in den Klassenvariablen gespeichert; aus dem Tabellenzeilenobjekt werden außerdem die Zeiger auf die Hintergrund- und Vordergrundzeichenflächen sowie auf das Zeichenobjekt übernommen.
Das Tabellenmodellobjekt verfügt ebenfalls über eigene Zeilen und Zellen. Dieser Klasse ist ein Tabellenzellenmodell zugewiesen, und sie zeichnet Daten aus dem Zellenmodell auf die Zeichenfläche des Zeilenobjekts.
Eine Methode zur Zuweisung des Zellenmodells:
//+------------------------------------------------------------------+ //| CTableCellView::Assigns a cell model | //+------------------------------------------------------------------+ bool CTableCellView::TableCellModelAssign(CTableCell *cell_model,int dx,int dy,int w,int h) { //--- If an invalid cell model object is passed, report this and return 'false' if(cell_model==NULL) { ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__); return false; } //--- If the base element (table row) is not assigned, report this and return 'false' if(this.m_element_base==NULL) { ::PrintFormat("%s: Error. Base element not assigned. Please use RowAssign() method first",__FUNCTION__); return false; } //--- Save the cell model this.m_table_cell_model=cell_model; //--- Set the coordinates and dimensions of the cell visual representation this.BoundSetXY(dx,dy); this.BoundResize(w,h); //--- Set the dimensions of the drawing area of the cell visual representation this.m_painter.SetBound(dx,dy,w,h); //--- All is successful return true; }
Zunächst wird die Gültigkeit des übergebenen Zeigers auf das Zellenmodell überprüft, anschließend wird geprüft, ob die Tabellenzeile diesem Zellenobjekt bereits zugewiesen wurde. Schlägt eine dieser Prüfungen fehl, wird dies im Protokoll vermerkt und false zurückgegeben. Anschließend wird der Zeiger auf das Zellenmodell in einer Variablen gespeichert, und die Koordinaten sowie die Abmessungen des Zellenbereichs in der entsprechenden Zeile werden festgelegt.
Beim Neuanordnen der Zeilen und Spalten der Tabelle wird der Zeiger auf das Zellenobjekt einfach neu zugewiesen, und dieses Objekt, das über seine genauen Koordinaten in der Tabelle verfügt, zeichnet die Daten der ihm neu zugewiesenen Zelle.
Eine Methode, die je nach Ankerpunkt die X- und Y-Koordinaten des Textes zurückgibt:
//+------------------------------------------------------------------+ //| CTableCellView::Return the X and Y coordinates of the text | //| depending on the anchor point | //+------------------------------------------------------------------+ bool CTableCellView::GetTextCoordsByAnchor(int &x,int &y) { //--- Get the text size in the cell int text_w=0, text_h=0; this.m_foreground.TextSize(this.Text(),text_w,text_h); if(text_w==0 || text_h==0) return false; //--- Depending on the text anchor point in the cell, //--- calculate its initial coordinates (upper left corner) switch(this.m_text_anchor) { //--- Anchor point left centered case ANCHOR_LEFT : x=0; y=(this.Height()-text_h)/2; break; //--- Anchor point in the lower left corner case ANCHOR_LEFT_LOWER : x=0; y=this.Height()-text_h; break; //--- Anchor point at the bottom center case ANCHOR_LOWER : x=(this.Width()-text_w)/2; y=this.Height()-text_h; break; //--- Anchor point in the lower right corner case ANCHOR_RIGHT_LOWER : x=this.Width()-text_w; y=this.Height()-text_h; break; //--- Anchor point is right centered case ANCHOR_RIGHT : x=this.Width()-text_w; y=(this.Height()-text_h)/2; break; //--- Anchor point in the upper right corner case ANCHOR_RIGHT_UPPER : x=this.Width()-text_w; y=0; break; //--- Anchor point at top center case ANCHOR_UPPER : x=(this.Width()-text_w)/2; y=0; break; //--- Anchor point is strictly in the center of the object case ANCHOR_CENTER : x=(this.Width()-text_w)/2; y=(this.Height()-text_h)/2; break; //--- Anchor point in the upper left corner //---ANCHOR_LEFT_UPPER default: x=0; y=0; break; } return true; }
Der Methode werden Variablen per Referenz übergeben, in die die berechneten Koordinaten der linken oberen Ecke des auszugebenden Textes geschrieben werden. Wenn die Ermittlung der Größe des Zellentextes fehlschlägt, gibt die Methode false zurück.
Nach der Berechnung der Koordinaten der oberen linken Ecke werden die berechneten Koordinaten des Textes in die Variablen geschrieben und true zurückgegeben.
Eine Methode zum Festlegen des Ankerpunkts des Textes:
//+------------------------------------------------------------------+ //| CTableCellView::Set the text anchor point | //+------------------------------------------------------------------+ void CTableCellView::SetTextAnchor(const ENUM_ANCHOR_POINT anchor,const bool cell_redraw,const bool chart_redraw) { if(this.m_text_anchor==anchor) return; this.m_text_anchor=anchor; if(cell_redraw) this.Draw(chart_redraw); }
Zunächst wird ein neuer Ankerpunkt in die Variable geschrieben; ist anschließend das Neuzeichnungsflag für diese Zelle gesetzt, wird die Methode zum Zeichnen dieser Zelle mit dem angegebenen Flag für die Neuzeichnung des Charts aufgerufen.
Eine Methode zur Festlegung des Ankerpunkts und der Textverschiebung:
//+------------------------------------------------------------------+ //| CTableCellView::Set the anchor point and text offsets | //+------------------------------------------------------------------+ void CTableCellView::SetTextPosition(const ENUM_ANCHOR_POINT anchor,const int shift_x,const int shift_y,const bool cell_redraw,const bool chart_redraw) { this.SetTextShiftX(shift_x); this.SetTextShiftY(shift_y); this.SetTextAnchor(anchor,cell_redraw,chart_redraw); }
Bei dieser Methode werden neben der Festlegung des Ankerpunkts auch die anfänglichen Textverschiebungen entlang der X- und Y-Achse festgelegt.
Eine Methode, mit der ein Objekt mit einer Farbe gefüllt wird:
//+------------------------------------------------------------------+ //| CTableCellView::Fill an object with color | //+------------------------------------------------------------------+ void CTableCellView::Clear(const bool chart_redraw) { //--- Set the correct coordinates of the cell corners int x1=this.AdjX(this.m_bound.X()); int y1=this.AdjY(this.m_bound.Y()); int x2=this.AdjX(this.m_bound.Right()); int y2=this.AdjY(this.m_bound.Bottom()); //--- Erase the background and foreground inside the rectangular area of the cell location if(this.m_background!=NULL) this.m_background.FillRectangle(x1,y1,x2,y2-1,::ColorToARGB(this.m_element_base.BackColor(),this.m_element_base.AlphaBG())); if(this.m_foreground!=NULL) this.m_foreground.FillRectangle(x1,y1,x2,y2-1,clrNULL); }
Ermitteln Sie die korrekten Koordinaten der vier Ecken des rechteckigen Bereichs. Füllen Sie dann den Hintergrund mit der Hintergrundfarbe der Tabellenzeile und den Vordergrund mit einer transparenten Farbe.
Eine Methode, die ein Objekt aktualisiert, um Änderungen anzuzeigen:
//+------------------------------------------------------------------+ //| CTableCellView::Update the object to reflect changes | //+------------------------------------------------------------------+ void CTableCellView::Update(const bool chart_redraw) { if(this.m_background!=NULL) this.m_background.Update(false); if(this.m_foreground!=NULL) this.m_foreground.Update(chart_redraw); }
Wenn die Zeichenflächen für Hintergrund und Vordergrund gültig sind, werden ihre Aktualisierungsmethoden mit dem angegebenen Flag für die Neuzeichnung des Charts aufgerufen.
Eine Methode zum Zeichnen der Zellenansicht:
//+------------------------------------------------------------------+ //| CTableCellView::Draw the appearance | //+------------------------------------------------------------------+ void CTableCellView::Draw(const bool chart_redraw) { //--- Get the text coordinates depending on the anchor point int text_x=0, text_y=0; if(!this.GetTextCoordsByAnchor(text_x,text_y)) return; //--- Correct the text coordinates int x=this.AdjX(this.X()+text_x); int y=this.AdjY(this.Y()+text_y); //--- Set the coordinates of the dividing line int x1=this.AdjX(this.X()); int x2=this.AdjX(this.X()); int y1=this.AdjY(this.Y()); int y2=this.AdjY(this.Bottom()); //--- Display text on the foreground canvas without updating the chart this.DrawText(x+this.m_text_x,y+this.m_text_y,this.Text(),false); //--- If this is not the rightmost cell, draw a vertical dividing line near the cell on the right 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); }
Die Logik der Methode wird in den Kommentaren erläutert. Eine Korrektur der Koordinaten ist erforderlich, wenn das Objekt entlang der Begrenzungen des Containers beschnitten wird. In diesem Fall werden die Anfangskoordinaten nicht anhand der tatsächlichen Koordinaten des grafischen Zeichenflächenobjekts berechnet, sondern anhand der Koordinaten des grafischen Elements, die virtuell außerhalb der Containergrenzen liegen.
Trennlinien werden nur auf der rechten Seite der Zelle eingezeichnet. Und wenn es sich nicht um die Zelle ganz rechts handelt, wird sie durch ihren Container begrenzt, und es ist nicht sinnvoll, dort eine zusätzliche Linie zu zeichnen.
Eine Methode zur Anzeige des Zellentextes:
//+------------------------------------------------------------------+ //| CTableCellView::Display the text | //+------------------------------------------------------------------+ void CTableCellView::DrawText(const int dx,const int dy,const string text,const bool chart_redraw) { //--- Check the base element if(this.m_element_base==NULL) return; //--- Clear the cell and set the text this.Clear(false); this.SetText(text); //--- Display the specified text on the foreground canvas this.m_foreground.TextOut(dx,dy,this.Text(),::ColorToARGB(this.m_element_base.ForeColor(),this.m_element_base.AlphaFG())); //--- If the text extends beyond the right border of the cell area if(this.Right()-dx<this.m_foreground.TextWidth(text)) { //--- Get the dimensions of the "..." text int w=0,h=0; this.m_foreground.TextSize("... ",w,h); if(w>0 && h>0) { //--- Erase the text at the right edge of the object to the size of the "..." text and replace the end of the label text with "..." this.m_foreground.FillRectangle(this.AdjX(this.Right())-w,this.AdjY(this.Y()),this.AdjX(this.Right()),this.AdjY(this.Y())+h,clrNULL); this.m_foreground.TextOut(this.AdjX(this.Right())-w,this.AdjY(dy),"...",::ColorToARGB(this.m_element_base.ForeColor(),this.m_element_base.AlphaFG())); } } //--- Update the foreground canvas with the specified chart redraw flag this.m_foreground.Update(chart_redraw); }
Die Logik der Methode wird in den Kommentaren zum Code ausführlich erläutert. Wenn der ausgegebene Text über den Zellbereich hinausragt, wird er an dessen Grenzen beschnitten und sein Ende durch Auslassungspunkte („...“) ersetzt, um anzuzeigen, dass die Zellenbreite nicht für den gesamten Text ausreicht.
Eine Methode, die das zugewiesene Zellenmodell in das Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableCellView::Print the assigned row model in the journal | //+------------------------------------------------------------------+ void CTableCellView::TableCellModelPrint(void) { if(this.m_table_cell_model!=NULL) this.m_table_cell_model.Print(); }
Mit dieser Methode können Sie überprüfen, welche Zelle der Modellkomponente der Zelle der Ansichtskomponente zugeordnet ist.
Eine Methode für Dateioperationen:
//+------------------------------------------------------------------+ //| CTableCellView::Save to file | //+------------------------------------------------------------------+ bool CTableCellView::Save(const int file_handle) { //--- Save the parent object data if(!CBaseObj::Save(file_handle)) return false; //--- Save the cell number if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE) return false; //--- Save the text anchor point if(::FileWriteInteger(file_handle,this.m_text_anchor,INT_VALUE)!=INT_VALUE) return false; //--- Save the text X coordinate if(::FileWriteInteger(file_handle,this.m_text_x,INT_VALUE)!=INT_VALUE) return false; //--- Save the text Y coordinate if(::FileWriteInteger(file_handle,this.m_text_y,INT_VALUE)!=INT_VALUE) return false; //--- Save the text if(::FileWriteArray(file_handle,this.m_text)!=sizeof(this.m_text)) return false; //--- All is successful return true; } //+------------------------------------------------------------------+ //| CTableCellView::Load from file | //+------------------------------------------------------------------+ bool CTableCellView::Load(const int file_handle) { //--- Load parent object data if(!CBaseObj::Load(file_handle)) return false; //--- Load the cell index this.m_id=this.m_index=::FileReadInteger(file_handle,INT_VALUE); //--- Load the text anchor point this.m_text_anchor=(ENUM_ANCHOR_POINT)::FileReadInteger(file_handle,INT_VALUE); //--- Load the text X coordinate this.m_text_x=::FileReadInteger(file_handle,INT_VALUE); //--- Load the text Y coordinate this.m_text_y=::FileReadInteger(file_handle,INT_VALUE); //--- Load the text if(::FileReadArray(file_handle,this.m_text)!=sizeof(this.m_text)) return false; //--- All is successful return true; }
Mit diesen Methoden können Sie die Daten der Tabellenzelle in einer Datei speichern und aus dieser Datei wieder laden.
Schauen wir uns nun die Klasse zur visuellen Darstellung einer Tabellenzeile an.
Tabellenzeilenklasse (Ansicht)
Eine Tabellenzeile ist ein Objekt, das von der Panelklasse abgeleitet ist. Es enthält eine Liste von Zellenobjekten der Klasse „CTableCellView“.
Fahren Sie mit dem Schreiben des Codes in der Datei „Controls.mqh“ fort:
//+------------------------------------------------------------------+ //| 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; // Cell list int m_index; // Index in the list of rows //--- Create and add a new cell representation object to the list CTableCellView *InsertNewCellView(const int index,const string text,const int dx,const int dy,const int w,const int h); public: //--- Reutrn the (1) list and (2) the number of cells CListElm *GetListCells(void) { return &this.m_list_cells; } int CellsTotal(void) const { return this.m_list_cells.Total(); } //--- Set the ID virtual void SetID(const int id) { this.m_index=this.m_id=id; } //--- (1) Set and (2) return the row index void SetIndex(const int index) { this.SetID(index); } int Index(void) const { return this.m_index; } //--- (1) Set and (2) return the row model bool TableRowModelAssign(CTableRow *row_model); CTableRow *GetTableRowModel(void) { return this.m_table_row_model; } //--- Print the assigned row model in the journal 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 of (1) comparing, (2) saving to file, (3) loading from 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); } //--- Initialize (1) the class object and (2) default object colors void Init(void); virtual void InitColors(void); //--- 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){} };
Eine Tabellenzeile weist dieselbe Eigenschaft wie eine Zelle auf: Ihr Zeilenindex entspricht ihrer Kennung. Auch hier wird die virtuelle Methode zum Festlegen der Kennung überschrieben; sie legt beide Eigenschaften gleichzeitig fest – den Index und die Kennung.
In den Klassenkonstruktoren wird die Methode zur Objektinitialisierung aufgerufen:
//+----------------------------------------------------------------------+ //| CTableRowView::Default constructor. Builds an object in the main | //| window of the current chart at coordinates 0,0 with default dimension| //+----------------------------------------------------------------------+ CTableRowView::CTableRowView(void) : CPanel("TableRow","",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H), m_index(-1) { //--- Initialization this.Init(); } //+----------------------------------------------------------------------------------+ //| CTableRowView::Parametric constructor. Builds an object in | //| 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) { //--- Initialization this.Init(); }
Objektinitialisierung:
//+------------------------------------------------------------------+ //| CTableRowView::Initialization | //+------------------------------------------------------------------+ void CTableRowView::Init(void) { //--- Initialize the parent object CPanel::Init(); //--- background - opaque this.SetAlphaBG(255); //--- Border width this.SetBorderWidth(1); }
Methode zur Initialisierung der Standardfarben des Objekts:
//+------------------------------------------------------------------+ //| CTableRowView::Initialize the object default colors | //+------------------------------------------------------------------+ void CTableRowView::InitColors(void) { //--- Initialize the background colors for the normal and activated states and make it the current background color this.InitBackColors(clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke); this.InitBackColorsAct(clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke); this.BackColorToDefault(); //--- Initialize the foreground colors for the normal and activated states and make it 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 make it 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); }
Eine Methode, die ein neues Zellenansichtsobjekt implementiert und der Liste hinzufügt:
//+------------------------------------------------------------------+ //| CTableRowView::Create and add a new | //| cell representation object to the list | //+------------------------------------------------------------------+ CTableCellView *CTableRowView::InsertNewCellView(const int index,const string text,const int dx,const int dy,const int w,const int h) { //--- Check whether the list contains an object with the specified ID and, if it does, report this and return NULL this.m_temp_cell.SetIndex(index); //--- Set the sorting flag for the list by ID this.m_list_cells.Sort(ELEMENT_SORT_BY_ID); if(this.m_list_cells.Search(&this.m_temp_cell)!=NULL) { ::PrintFormat("%s: Error. The TableCellView object with index %d is already in the list",__FUNCTION__,index); return NULL; } //--- Create a name and ID for the cell object string name="TableCellView"+(string)this.Index()+"x"+(string)index; int id=this.m_list_cells.Total(); //--- Create a new TableCellView object; in case of a failure, report it and return NULL CTableCellView *cell_view=new CTableCellView(id,name,""+text,dx,dy,w,h); if(cell_view==NULL) { ::PrintFormat("%s: Error. Failed to create CTableCellView object",__FUNCTION__); return NULL; } //--- If failed to add the new object to the list, report this, remove the object and return NULL if(this.m_list_cells.Add(cell_view)==-1) { ::PrintFormat("%s: Error. Failed to add CTableCellView object to list",__FUNCTION__); delete cell_view; return NULL; } //--- Assign the base element and return the pointer to the object cell_view.RowAssign(this.GetObject()); return cell_view; }
Jeder Zelle wird ein eigener Bereich des Tabellenzeilenobjekts zugewiesen; darüber hinaus müssen die mit dem Operator new erstellten Objekte in der Liste gespeichert werden, andernfalls müssen Sie sie selbst nachverfolgen und bei Bedarf löschen.
Es ist einfacher, sie in einer Liste zu speichern – dann kümmert sich das Terminalsubsystem selbst darum, wann sie gelöscht werden müssen. Die Methode erstellt ein neues Zellenansichtsobjekt und fügt es in die Liste der Zeilenzellen ein. Nach seiner Erstellung werden dem Objekt die Zeile, in der es sich befindet, sowie die Zeichenflächen zugewiesen, auf denen es die Modelldaten der Tabellenzelle zeichnet.
Die Methode, die das Zeilenmodell festlegt:
//+------------------------------------------------------------------+ //| CTableRowView::Set the row model | //+------------------------------------------------------------------+ bool CTableRowView::TableRowModelAssign(CTableRow *row_model) { //--- If an empty object is passed, report this and return 'false' if(row_model==NULL) { ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__); return false; } //--- If the passed row model does not contain a single cell, report this and return 'false' int total=(int)row_model.CellsTotal(); if(total==0) { ::PrintFormat("%s: Error. Row model does not contain any cells",__FUNCTION__); return false; } //--- Save the pointer to the passed row model and calculate the cell width this.m_table_row_model=row_model; int cell_w=(int)::round((double)this.Width()/(double)total); //--- In the loop by the number of cells in the row model for(int i=0;i<total;i++) { //--- get the model of the next cell, CTableCell *cell_model=this.m_table_row_model.GetCell(i); if(cell_model==NULL) return false; //--- calculate the coordinate and create a name for the cell area int x=cell_w*i; string name="CellBound"+(string)this.m_table_row_model.Index()+"x"+(string)i; //--- Create a new cell area CBound *cell_bound=this.InsertNewBound(name,x,0,cell_w,this.Height()); if(cell_bound==NULL) return false; //--- Create a new cell visual representation object CTableCellView *cell_view=this.InsertNewCellView(i,cell_model.Value(),x,0,cell_w,this.Height()); if(cell_view==NULL) return false; //--- Assign the corresponding visual representation object of the cell to the current cell area cell_bound.AssignObject(cell_view); } //--- All is successful return true; }
Der Methode wird ein Zeiger auf das Zeilenmodell übergeben. In einer Schleife mit einem Durchlauf pro Zelle im Modell werden neue Bereiche für die Zellenansichtsobjekte sowie die Zellen selbst (Klasse „CTableCellView“) erstellt. Jede so erstellte Zelle wird dem zugehörigen neuen Bereich zugeordnet. Am Ende erhalten wir eine Liste von Zellbereichen, denen Zeiger auf die entsprechenden Tabellenzellen zugeordnet sind.
Eine Methode zum Zeichnen der Zeilenansicht:
//+------------------------------------------------------------------+ //| CTableRowView::Draw the appearance | //+------------------------------------------------------------------+ void CTableRowView::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())); //--- Draw the row cells int total=this.m_list_bounds.Total(); for(int i=0;i<total;i++) { //--- Get the area of the next cell CBound *cell_bound=this.GetBoundAt(i); if(cell_bound==NULL) continue; //--- Get the attached cell object from the cell area CTableCellView *cell_view=cell_bound.GetAssignedObj(); //--- Draw a visual representation of the cell if(cell_view!=NULL) cell_view.Draw(false); } //--- Update the background and foreground canvases with the specified chart redraw flag this.Update(chart_redraw); }
Zunächst wird die Zeile mit der Hintergrundfarbe gefüllt und an ihrem unteren Rand eine Linie gezeichnet. Anschließend durchlaufen wir in einer Schleife die Zellenbereiche der Zeile, holen uns den nächsten Zellenbereich, erhalten daraus einen Zeiger auf das Zellenobjekt und rufen dessen Zeichnungsmethode auf.
Eine Methode, die das zugewiesene Zeilenmodell in das Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableRowView::Print the assigned row model in the journal | //+------------------------------------------------------------------+ void CTableRowView::TableRowModelPrint(const bool detail, const bool as_table=false, const int cell_width=CELL_WIDTH_IN_CHARS) { if(this.m_table_row_model!=NULL) this.m_table_row_model.Print(detail,as_table,cell_width); }
Mit dieser Methode können Sie überprüfen, welches Zeilenmodell aus dem Tabellenmodell diesem Objekt zur visuellen Darstellung einer Zeile zugewiesen ist.
Eine Methode für Dateioperationen:
//+------------------------------------------------------------------+ //| CTableRowView::Save to file | //+------------------------------------------------------------------+ bool CTableRowView::Save(const int file_handle) { //--- Save the parent object 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 index if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE) return false; //--- All is successful return true; } //+------------------------------------------------------------------+ //| CTableRowView::Load from file | //+------------------------------------------------------------------+ bool CTableRowView::Load(const int file_handle) { //--- Load parent object data 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 index this.m_id=this.m_index=(uchar)::FileReadInteger(file_handle,INT_VALUE); //--- All is successful return true; }
Mit diesen Methoden können Sie die Daten einer Tabellenzeile in einer Datei speichern und aus dieser Datei wieder laden.
Jede Tabelle muss einen Tabellenkopf haben. So können Sie nachvollziehen, welche Daten in den Spalten der Tabelle angezeigt werden. Ein Tabellenkopf ist eine Liste von Spaltenüberschriften. Jede Spalte der Tabelle hat eine eigene Spaltenüberschrift, in der der Typ und der Name der in der Spalte enthaltenen Daten angezeigt werden.
Klasse für Spaltenüberschriften der Tabelle (Ansicht)
Die Spaltenüberschrift der Tabelle ist ein eigenständiges Objekt, das vom Objekt „Button“ (CButton) abgeleitet ist, dessen Verhalten es übernimmt und ergänzt. In der aktuellen Umsetzung werden die Eigenschaften der Schaltfläche nicht erweitert – wir ändern lediglich die Farben der verschiedenen Zustände. Im nächsten Artikel werden wir die Spaltenüberschrift um eine Anzeige der Sortierrichtung – Aufwärts- und Abwärtspfeile auf der rechten Seite des Schaltflächenbereichs – sowie um ein Ereignismodell erweitern, mit dem die Sortierung durch Klicken auf die Schaltfläche gestartet wird.
Fahren Sie mit dem Schreiben des Codes in der Datei „Controls.mqh“ fort:
//+------------------------------------------------------------------+ //| Class for visual representation of table column header | //+------------------------------------------------------------------+ class CColumnCaptionView : public CButton { protected: CColumnCaption *m_column_caption_model; // Pointer to the column header model int m_index; // Index in the column list public: //--- Set the ID virtual void SetID(const int id) { this.m_index=this.m_id=id; } //--- (1) Set and (2) return the cell index void SetIndex(const int index) { this.SetID(index); } int Index(void) const { return this.m_index; } //--- (1) Assign and (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 in the journal void ColumnCaptionModelPrint(void); //--- Draw the appearance virtual void Draw(const bool chart_redraw); //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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); } //--- Initialize (1) the class object and (2) default object colors void Init(const string text); virtual void InitColors(void); //--- Return the object description 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){} };
Die Methode hat einen Index, der der Kennung entspricht, wie bei den beiden zuvor betrachteten Klassen. Auch die Methode zum Festlegen der Kennung ist ähnlich wie bei den vorherigen Klassen.
In den Klassenkonstruktoren wird die Methode zur Objektinitialisierung aufgerufen und die Kennung auf null gesetzt (sie ändert sich nach der Erstellung des Objekts):
//+------------------------------------------------------------------+ //| CColumnCaptionView::Default constructor. Builds an object | //| in the main window of the current chart at coordinates 0,0 | //| with default dimensions | //+------------------------------------------------------------------+ CColumnCaptionView::CColumnCaptionView(void) : CButton("ColumnCaption","Caption",::ChartID(),0,0,0,DEF_PANEL_W,DEF_TABLE_ROW_H), m_index(0) { //--- Initialization this.Init("Caption"); this.SetID(0); this.SetName("ColumnCaption"); } //+------------------------------------------------------------------+ //| CColumnCaptionView::Parametric constructor. | //| Plot an object in the specified window of the specified plot 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) : CButton(object_name,text,chart_id,wnd,x,y,w,h), m_index(0) { //--- Initialization this.Init(text); this.SetID(0); }
Methode zur Objektinitialisierung:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Initialization | //+------------------------------------------------------------------+ void CColumnCaptionView::Init(const string text) { //--- Default text offsets this.m_text_x=4; this.m_text_y=2; //--- Set the colors of different states this.InitColors(); }
Methode zur Initialisierung der Standardfarben des Objekts:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Initialize the object default colors | //+------------------------------------------------------------------+ void CColumnCaptionView::InitColors(void) { //--- Initialize the background colors for the normal and activated states and make it the current background color this.InitBackColors(clrWhiteSmoke,this.GetBackColorControl().NewColor(clrWhiteSmoke,-6,-6,-6),clrWhiteSmoke,clrWhiteSmoke); this.InitBackColorsAct(clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke); this.BackColorToDefault(); //--- Initialize the foreground colors for the normal and activated states and make it 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 make it 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); }
Methode zum Zeichnen der Ansicht der Spaltenüberschrift:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Draw the appearance | //+------------------------------------------------------------------+ void CColumnCaptionView::Draw(const bool chart_redraw) { //--- Fill the button with the background color, draw the light vertical line on the left and the 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); }
Zunächst wird der Hintergrund mit der festgelegten Farbe ausgefüllt, dann werden zwei vertikale Linien gezeichnet – eine helle auf der linken Seite und eine dunkle auf der rechten Seite. Anschließend wird der Text der Spaltenüberschrift auf der Zeichenfläche des Vordergrunds angezeigt.
Eine Methode, die eine Beschreibung des Objekts zurückgibt:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Return the object description | //+------------------------------------------------------------------+ string CColumnCaptionView::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()); }
Die Methode gibt eine Beschreibung des Elementtyps mit der ID, den Koordinaten und den Abmessungen des Objekts zurück.
Methode zur Zuweisung des Modell der Spaltenüberschrifts:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Assign the column caption model | //+------------------------------------------------------------------+ bool CColumnCaptionView::ColumnCaptionModelAssign(CColumnCaption *caption_model) { //--- If an invalid column header model object is passed, report this 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 of the column header visual representation this.m_painter.SetBound(0,0,this.Width(),this.Height()); //--- All is successful return true; }
Ein Zeiger auf das Modell der Spaltenüberschrift wird an die Methode übergeben und in einer Variablen gespeichert. Anschließend werden die Koordinaten und Abmessungen des Zeichenbereichs für das Zeichnungsobjekt festgelegt.
Eine Methode, die das zugewiesene Modell der Spaltenüberschrift im Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Print in the journal | //| the assigned column header model | //+------------------------------------------------------------------+ void CColumnCaptionView::ColumnCaptionModelPrint(void) { if(this.m_column_caption_model!=NULL) this.m_column_caption_model.Print(); }
Die Methode ermöglicht die Überprüfung des zugewiesenen Modell der Spaltenüberschrifts, indem sie dessen Beschreibung im Protokoll ausgibt; das Modell ist dem Objekt zur visuellen Darstellung der Spaltenüberschrift zugewiesen.
Eine Methode für Dateioperationen:
//+------------------------------------------------------------------+ //| CColumnCaptionView::Save to file | //+------------------------------------------------------------------+ bool CColumnCaptionView::Save(const int file_handle) { //--- Save the parent object data if(!CButton::Save(file_handle)) return false; //--- Save the header index if(::FileWriteInteger(file_handle,this.m_index,INT_VALUE)!=INT_VALUE) return false; //--- All is successful return true; } //+------------------------------------------------------------------+ //| CColumnCaptionView::Load from file | //+------------------------------------------------------------------+ bool CColumnCaptionView::Load(const int file_handle) { //--- Load parent object data if(!CButton::Load(file_handle)) return false; //--- Load the header index this.m_id=this.m_index=::FileReadInteger(file_handle,INT_VALUE); //--- All is successful return true; }
Sie bieten eine Funktion zum Speichern der Parameter der Spaltenüberschrift in einer Datei und zum Laden dieser Parameter aus einer Datei.
Tabellenkopfklasse (Ansicht)
Der Tabellenkopf ist eine einfache Liste von Spaltenüberschriftenobjekten auf Basis des Panel-Steuerelements (CPanel). Folglich bietet ein solches Objekt Werkzeuge zur Verwaltung von Tabellenspalten.
In dieser Implementierung handelt es sich um ein normales statisches Objekt. Alle Funktionen zur Benutzerinteraktion werden später hinzugefügt.
Schreiben Sie den Code in derselben Datei weiter:
//+------------------------------------------------------------------+ //| Class for visual representation of table header | //+------------------------------------------------------------------+ 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 //--- Create and add a new column header representation object to the list CColumnCaptionView *InsertNewColumnCaptionView(const string text, const int x, const int y, const int w, const int h); public: //--- (1) Set and (2) return the table header model bool TableHeaderModelAssign(CTableHeader *header_model); CTableHeader *GetTableHeaderModel(void) { return this.m_table_header_model; } //--- Print the assigned table header model in the journal void TableHeaderModelPrint(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 of (1) comparing, (2) saving to file, (3) loading from 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); } //--- Initialize (1) the class object and (2) default object 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){} };
Dem Objekt wird ein Modell der Spaltenüberschrift zugewiesen; anhand seines Inhalts werden Spaltenüberschriftenobjekte erstellt und der Liste der angehängten Elemente hinzugefügt.
In den Klassenkonstruktoren wird die Methode zur Objektinitialisierung aufgerufen:
//+------------------------------------------------------------------+ //| CTableHeaderView::Default constructor. Builds an object in | //| in the main 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) { //--- Initialization this.Init(); } //+----------------------------------------------------------------------------------+ //| CTableHeaderView::Parametric constructor. Builds an object in | //| in the specified 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) { //--- Initialization this.Init(); }
Methode zur Objektinitialisierung:
//+------------------------------------------------------------------+ //| CTableHeaderView::Initialization | //+------------------------------------------------------------------+ void CTableHeaderView::Init(void) { //--- Initialize the parent object CPanel::Init(); //--- Background color - opaque this.SetAlphaBG(255); //--- Border width this.SetBorderWidth(1); }
Methode zur Initialisierung der Standardfarben des Objekts:
//+------------------------------------------------------------------+ //| CTableHeaderView::Initialize the object default colors | //+------------------------------------------------------------------+ void CTableHeaderView::InitColors(void) { //--- Initialize the background colors for the normal and activated states and make it the current background color this.InitBackColors(clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke); this.InitBackColorsAct(clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke,clrWhiteSmoke); this.BackColorToDefault(); //--- Initialize the foreground colors for the normal and activated states and make it 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 make it 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); }
Eine Methode, die ein neues Zellenansichtsobjekt erstellt und der Liste hinzufügt:
//+------------------------------------------------------------------+ //| CTableHeaderView::Create and add to the list | //| new column header representation object | //+------------------------------------------------------------------+ CColumnCaptionView *CTableHeaderView::InsertNewColumnCaptionView(const string text,const int x,const int y,const int w,const int h) { //--- Create an object name and return the result of creating a new column header string user_name="ColumnCaptionView"+(string)this.m_list_elm.Total(); CColumnCaptionView *caption_view=this.InsertNewElement(ELEMENT_TYPE_TABLE_COLUMN_CAPTION,text,user_name,x,y,w,h); return(caption_view!=NULL ? caption_view : NULL); }
Das Spaltenüberschriftenobjekt wird mithilfe der Standardmethode InsertNewElement() für Bibliotheksobjekte erstellt, die die erstellten Objekte in die Liste der UI-Elemente des Objekts einfügt.
Eine Methode zum Festlegen des Modell der Spaltenüberschrifts:
//+------------------------------------------------------------------+ //| CTableHeaderView::Set 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 does not contain any 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)::round((double)this.Width()/(double)total); //--- In the loop by the number of column headers in the table header model for(int i=0;i<total;i++) { //--- get the model of the next column header, 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; //--- Create a new column header visual representation object CColumnCaptionView *caption_view=this.InsertNewColumnCaptionView(caption_model.Value(),x,0,caption_w,this.Height()); if(caption_view==NULL) return false; //--- Assign the corresponding visual representation object of the column header to the current column header area caption_bound.AssignObject(caption_view); } //--- All is successful return true; }
Das Modell der Spaltenüberschrift wird an die Methode übergeben. Erstellen Sie in einer Schleife für jede Spaltenüberschrift im Modell einen weiteren Bereich, in dem die jeweilige Spaltenüberschrift platziert werden soll. Erstellen Sie ein Spaltenüberschriftenobjekt und weisen Sie es dem aktuellen Bereich zu. Nach Abschluss der Schleife verfügen wir über eine Liste von Bereichen, denen Spaltenüberschriften zugewiesen sind.
Eine Methode zum Zeichnen der Ansicht des Tabellenkopfs:
//+------------------------------------------------------------------+ //| CTableHeaderView::Draw the appearance | //+------------------------------------------------------------------+ void CTableHeaderView::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 column headers int total=this.m_list_bounds.Total(); for(int i=0;i<total;i++) { //--- Get the area of the next column header CBound *cell_bound=this.GetBoundAt(i); if(cell_bound==NULL) continue; //--- Get the attached column header object from the column header area CColumnCaptionView *caption_view=cell_bound.GetAssignedObj(); //--- Draw a visual representation of the column header if(caption_view!=NULL) caption_view.Draw(false); } //--- If specified, update the chart if(chart_redraw) ::ChartRedraw(this.m_chart_id); }
Zunächst wird der gesamte Tabellenkopfbereich mit der Hintergrundfarbe ausgefüllt, anschließend wird am unteren Rand eine Trennlinie gezeichnet. Anschließend wird in einer Schleife über die Liste der Tabellenkopfbereiche jeweils der nächste Bereich abgerufen. Aus diesem Bereich wird dann das ihm zugeordnete Objekt für die Spaltenüberschrift abgerufen. Die Zeichenmethode dieses Objekts wird aufgerufen.
Eine Methode, die das zugewiesene Modell der Spaltenüberschrift in das Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableHeaderView::Print in the journal | //| the assigned table header model | //+------------------------------------------------------------------+ void CTableHeaderView::TableHeaderModelPrint(const bool detail,const bool as_table=false,const int cell_width=CELL_WIDTH_IN_CHARS) { if(this.m_table_header_model!=NULL) this.m_table_header_model.Print(detail,as_table,cell_width); }
Ermöglicht die Ausgabe des diesem Objekt zugewiesenen Modell der Spaltenüberschrifts im Protokoll.
Eine Tabelle – genauer gesagt ihre visuelle Darstellung – ist ein zusammengesetztes Objekt, das von seinem Modell Daten zur Tabelle und zum Tabellenkopf erhält und diese in verschiedenen Steuerelementen zeichnet. Es handelt sich um ein Panel, das einen Tabellenkopf und einen Container mit tabellarischen Daten (Tabellenzeilen) enthält.
Tabellenklasse (Ansicht)
Fahren Sie mit dem Schreiben des Codes in der Datei „Controls.mqh“ fort:
//+------------------------------------------------------------------+ //| Table visual representation class | //+------------------------------------------------------------------+ class CTableView : public CPanel { protected: //--- Obtained table data CTable *m_table_obj; // Pointer to table object (includes table and header models) CTableModel *m_table_model; // Pointer to the table model (obtained from CTable) CTableHeader *m_header_model; // Pointer to the table header model (obtained from CTable) //--- View component data CTableHeaderView *m_header_view; // Pointer to the table header (View) CPanel *m_table_area; // Panel for placing table rows CContainer *m_table_area_container; // Container for placing a panel with table rows //--- (1) Set and (2) return the table model bool TableModelAssign(CTableModel *table_model); CTableModel *GetTableModel(void) { return this.m_table_model; } //--- (1) Set and (2) return the table header model bool HeaderModelAssign(CTableHeader *header_model); CTableHeader *GetHeaderModel(void) { return this.m_header_model; } //--- Create a (1) header and (2) table object from the model bool CreateHeader(void); bool CreateTable(void); public: //--- (1) Set and (2) return the table object bool TableObjectAssign(CTable *table_obj); CTable *GetTableObj(void) { return this.m_table_obj; } //--- Print the assigned (1) table, (2) table header and (3) table object model in the journal 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); //--- Draw the appearance virtual void Draw(const bool chart_redraw); //--- Virtual methods of (1) comparing, (2) saving to file, (3) loading from 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); } //--- Initialize (1) the class object and (2) default object 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){} };
Die Klasse erbt von der Klasse des Panel-Objekts. Es sind drei Modellkomponenten und drei Ansichtskomponenten sichtbar. Die Klasse verfügt über Zeiger auf das Tabellenmodell, das Modell der Spaltenüberschrift und die Tabelle. Aus der Tabelle erhalten wir Zeiger auf die tabellarischen Daten und den Tabellenkopf. Außerdem gibt es drei Zeiger: einen auf den Tabellenkopf, einen auf das Tabellenzeilen-Panel und einen auf einen Container, in dem dieses Panel platziert wird.
Der springende Punkt ist, dass die Zeilen der Tabelle an das Panel-Objekt angehängt sind (es können mehrere Elemente angehängt werden) und dieses Panel wiederum an den Container angehängt ist (man kann ein einzelnes Element anhängen), in dem sich Bildlaufleisten befinden, mit denen man das Panel mit den Tabellenzeilen verschieben kann. Visuell besteht das Element somit aus einem Tabellenkopf und einer darunter liegenden, durch Bildlauf verschiebbaren Tabelle (Zeilen und Spalten, die aus Zellen gebildet werden).
Rufen Sie in den Konstruktoren der Klasse die Methode zur Objektinitialisierung auf:
//+------------------------------------------------------------------+ //| CTableView::Default constructor. | //| Builds an element in the main window of the current chart | //| at 0,0 coordinates 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_table_area(NULL),m_table_area_container(NULL) { //--- Initialization this.Init(); } //+------------------------------------------------------------------+ //| CTableView::Parametric constructor. | //| Builds an element in the specified 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_table_obj(NULL),m_header_view(NULL),m_table_area(NULL),m_table_area_container(NULL) { //--- Initialization this.Init(); }
Erstellen Sie in der Initialisierungsmethode alle erforderlichen Steuerelemente auf dem Panel des Objekts:
//+------------------------------------------------------------------+ //| CTableView::Initialization | //+------------------------------------------------------------------+ void CTableView::Init(void) { //--- Initialize the parent object CPanel::Init(); //--- Border width this.SetBorderWidth(1); //--- Create the table header this.m_header_view=this.InsertNewElement(ELEMENT_TYPE_TABLE_HEADER,"","TableHeader",0,0,this.Width(),DEF_TABLE_HEADER_H); if(this.m_header_view==NULL) return; this.m_header_view.SetBorderWidth(1); //--- Create a container that will contain the table row panel this.m_table_area_container=this.InsertNewElement(ELEMENT_TYPE_CONTAINER,"","TableAreaContainer",0,DEF_TABLE_HEADER_H,this.Width(),this.Height()-DEF_TABLE_HEADER_H); if(this.m_table_area_container==NULL) return; this.m_table_area_container.SetBorderWidth(0); this.m_table_area_container.SetScrollable(true); //--- Attach a panel to the container to store table rows int shift_y=0; this.m_table_area=this.m_table_area_container.InsertNewElement(ELEMENT_TYPE_PANEL,"","TableAreaPanel",0,shift_y,this.m_table_area_container.Width(),this.m_table_area_container.Height()-shift_y); if(m_table_area==NULL) return; this.m_table_area.SetBorderWidth(0); }
Eine Methode zum Festlegen des Tabellenmodells:
//+------------------------------------------------------------------+ //| CTableView::Set the table model | //+------------------------------------------------------------------+ bool CTableView::TableModelAssign(CTableModel *table_model) { if(table_model==NULL) { ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__); return false; } this.m_table_model=table_model; return true; }
Wir übergeben einfach einen Zeiger auf das Tabellenmodell-Objekt an die Methode und speichern ihn in einer Variablen, über die wir dann darauf zugreifen können.
Eine Methode zum Festlegen des Modell der Spaltenüberschrifts:
//+------------------------------------------------------------------+ //| CTableView::Set the table header model | //+------------------------------------------------------------------+ bool CTableView::HeaderModelAssign(CTableHeader *header_model) { if(header_model==NULL) { ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__); return false; } this.m_header_model=header_model; return true; }
Übergeben Sie der Methode einen Zeiger auf das Modell der Spaltenüberschriftobjekt und speichern Sie ihn in einer Variablen, über die wir auf das Objekt zugreifen.
Eine Methode zum Festlegen eines Tabellenobjekts:
//+------------------------------------------------------------------+ //| CTableView::Set the table object | //+------------------------------------------------------------------+ bool CTableView::TableObjectAssign(CTable *table_obj) { //--- If an empty table object is passed, report this and return 'false' if(table_obj==NULL) { ::PrintFormat("%s: Error. Empty object passed",__FUNCTION__); return false; } //--- Save the pointer to a variable this.m_table_obj=table_obj; //--- Set the result of assigning the table model and the header model bool res=this.TableModelAssign(this.m_table_obj.GetTableModel()); res &=this.HeaderModelAssign(this.m_table_obj.GetTableHeader()); //--- If failed to assign any model, return 'false' if(!res) return false; //--- Set the result of creating the table header from the model and the table from the model res=this.CreateHeader(); res&=this.CreateTable(); //--- Return the result return res; }
Ein Zeiger auf ein Tabellenobjekt wird an die Methode übergeben. Rufen Sie aus diesem Objekt das Modell der Spaltenüberschrift und das Tabellenmodell ab und weisen Sie diese zu. Erstellen Sie anschließend anhand der Daten aus dem Modell der Spaltenüberschrift und dem Tabellenmodell Objekte für die visuelle Darstellung des Tabellenkopfs und der Tabelle.
Eine Methode, die aus einem Modell ein Tabellenobjekt erstellt:
//+------------------------------------------------------------------+ //| CTableView::Create a table object from the model | //+------------------------------------------------------------------+ bool CTableView::CreateTable(void) { if(this.m_table_area==NULL) return false; //--- In a loop, create and attach RowsTotal rows from the TableRowView elements to the Panel (m_table_area) element int total=(int)this.m_table_model.RowsTotal(); int y=1; // Vertical offset int table_height=0; // Calculated panel height CTableRowView *row=NULL; for(int i=0;i<total;i++) { //--- Create and attach a table row object to the panel row=this.m_table_area.InsertNewElement(ELEMENT_TYPE_TABLE_ROW,"","TableRow"+(string)i,0,y+(row!=NULL ? row.Height()*i : 0),this.m_table_area.Width()-1,DEF_TABLE_ROW_H); if(row==NULL) return false; //--- Set the row ID row.SetID(i); //--- Set the row background color depending on its index (even/odd) if(row.ID()%2==0) row.InitBackColorDefault(clrWhite); else row.InitBackColorDefault(clrWhiteSmoke); row.BackColorToDefault(); row.InitBackColorFocused(row.GetBackColorControl().NewColor(row.BackColor(),-4,-4,-4)); //--- Get the row model from the table object CTableRow *row_model=this.m_table_model.GetRow(i); if(row_model==NULL) return false; //--- Assign the obtained row model to the created table row object row.TableRowModelAssign(row_model); //--- Calculate the new panel height value table_height+=row.Height(); } //--- Return the result of changing the panel size to the value calculated in the loop return this.m_table_area.ResizeH(table_height+y); }
Die Logik der Methode wird in den Kommentaren zum Code erläutert. Erstellen Sie in einer Schleife für jede Tabellenzeile im Tabellenmodell ein neues Tabellenzeilenobjekt und fügen Sie es dem Panel hinzu; berechnen Sie dabei gleichzeitig die spätere Höhe des Panels. Nachdem die Schleife durchlaufen und alle erforderlichen Tabellenzeilen erstellt wurden, wird die Höhe des Panels entsprechend der in der Schleife berechneten Größe angepasst.
Eine Methode zum Zeichnen der Tabellenansicht:
//+------------------------------------------------------------------+ //| CTableView::Draw the appearance | //+------------------------------------------------------------------+ void CTableView::Draw(const bool chart_redraw) { //--- Draw the table header and rows this.m_header_view.Draw(false); this.m_table_area_container.Draw(false); //--- If specified, update the chart if(chart_redraw) ::ChartRedraw(this.m_chart_id); }
Zeichnen Sie zunächst den Tabellenkopf und darunter die Tabellenzeilen im Container.
Eine Methode, die das zugewiesene Tabellenmodell in das Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableView::Print the assigned table model in the journal | //+------------------------------------------------------------------+ void CTableView::TableModelPrint(const bool detail) { if(this.m_table_model!=NULL) this.m_table_model.Print(detail); }
Damit lässt sich das zugewiesene Tabellenmodell in das Protokoll ausgeben.
Eine Methode, die das zugewiesene Modell der Spaltenüberschrift im Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableView::Print the assigned header model in the journal | //+------------------------------------------------------------------+ void CTableView::HeaderModelPrint(const bool detail,const bool as_table=false,const int column_width=CELL_WIDTH_IN_CHARS) { if(this.m_header_model!=NULL) this.m_header_model.Print(detail,as_table,column_width); }
Damit kann das zugewiesene Modell der Spaltenüberschrift in das Protokoll ausgegeben werden.
Eine Methode, die das zugewiesene Tabellenobjekt in das Protokoll ausgibt:
//+------------------------------------------------------------------+ //| CTableView::Print the assigned table object in the journal | //+------------------------------------------------------------------+ void CTableView::TablePrint(const int column_width=CELL_WIDTH_IN_CHARS) { if(this.m_table_obj!=NULL) this.m_table_obj.Print(column_width); }
Sie gibt die gesamte dem Objekt zugewiesene Tabelle einschließlich des Tabellenkopfs und der Daten im Protokoll aus.
Das war's – wir haben nun alle Klassen implementiert, um eine visuelle Darstellung des Tabellenmodells zu erstellen. Schauen wir uns einmal an, wie Sie nun aus einem Datenarray eine einfache Tabelle erstellen können.
Überprüfung des Ergebnisses
Erstellen Sie im Terminalverzeichnis \MQL5\Indicators\Tables\ einen neuen Indikator, der keine Puffer verwendet und in einem Chart-Unterfenster dargestellt wird:
//+------------------------------------------------------------------+ //| iTestTable.mq5 | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property indicator_separate_window #property indicator_buffers 0 #property indicator_plots 0
Binden Sie die Bibliothek in die Indikatordatei ein und deklarieren Sie Zeiger auf Objekte global:
//+------------------------------------------------------------------+ //| iTestTable.mq5 | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00" #property indicator_separate_window #property indicator_buffers 0 #property indicator_plots 0 //+------------------------------------------------------------------+ //| Include libraries | //+------------------------------------------------------------------+ #include "Controls\Controls.mqh" // Controls library CPanel *panel=NULL; // Pointer to the Panel graphical element CTable *table; // Pointer to table object (Model)
Schreiben Sie anschließend den folgenden Code in den OnInit()-Handler des Indikators:
//+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- Search for the chart subwindow int wnd=ChartWindowFind(); //--- Create the Panel graphical element panel=new CPanel("Panel","",0,wnd,100,40,400,192); if(panel==NULL) return INIT_FAILED; //--- Set the panel parameters panel.SetID(1); // ID panel.SetAsMain(); // The chart should have one main element panel.SetBorderWidth(1); // Border width (one pixel margin on each side of the container) panel.SetResizable(false); // Ability to resize by dragging edges and corners panel.SetName("Main container"); // Name //--- Create table data //--- Declare and fill the array of column headers with the dimension of 4 string captions[4]={"Column 0","Column 1","Column 2","Column 3"}; //--- Declare and fill the 10x4 data array //--- Acceptable array types: double, long, datetime, color, string long array[10][4]={{ 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}, {25, 26, 27, 28}, {29, 30, 31, 32}, {33, 34, 35, 36}, {37, 38, 39, 40}}; //--- Create a table object from the above created 10x4 long array and a string array of column headers (Model component) table=new CTable(array,captions); if(table==NULL) return INIT_FAILED; PrintFormat("The [%s] has been successfully created:",table.Description()); //--- Create a new element on the panel - a table (View component) CTableView *table_view=panel.InsertNewElement(ELEMENT_TYPE_TABLE,"","TableView",4,4,panel.Width()-8,panel.Height()-8); //--- Assign the table object (Model) to the Table graphical element (View) table_view.TableObjectAssign(table); //--- Print the table model in the journal table_view.TablePrint(); //--- Draw a table with a panel panel.Draw(true); //--- Successful return(INIT_SUCCEEDED); }
Hier sehen wir drei Codeabschnitte:
- Erstellen eines Panels, auf dem die Tabelle aufgebaut wird;
- Erstellen tabellarischer Daten in zwei Arrays – eines für die Tabelle und eines für den Tabellenkopf (Modellkomponenten);
- Erstellen einer Tabelle im Panel (Ansichtskomponente).
Tatsächlich sind zwei Schritte erforderlich, um eine Tabelle zu erstellen: das Erstellen der Daten (Punkt 2) und das Erstellen der Tabelle (Punkt 3). Das Panel dient lediglich der Dekoration und als Grundlage für ein grafisches Element.
Fügen Sie den restlichen Indikatorcode hinzu:
//+------------------------------------------------------------------+ //| Custom deindicator initialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- Remove the Panel element and destroy the table and library's shared resource manager delete panel; delete table; CCommonManager::DestroyInstance(); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int 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 int &spread[]) { //--- //--- return value of prev_calculated for the next call return(rates_total); } //+------------------------------------------------------------------+ //| ChartEvent function | //+------------------------------------------------------------------+ void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam) { //--- Call the OnChartEvent handler of the Panel element panel.OnChartEvent(id,lparam,dparam,sparam); } //+------------------------------------------------------------------+ //| Timer | //+------------------------------------------------------------------+ void OnTimer(void) { //--- Call the OnTimer handler of the Panel element panel.OnTimer(); }
Kompilieren Sie den Indikator und führen Sie ihn auf dem Chart aus:

Im Terminalprotokoll werden eine Meldung über die erfolgreiche Erstellung der Tabelle, eine Beschreibung der Tabelle sowie die Tabelle selbst mit einem Tabellenkopf ausgegeben:
The [Table: Rows total: 10, Columns total: 4] has been successfully created: Table: Rows total: 10, Columns total: 4: | n/n | Column 0 | Column 1 | Column 2 | Column 3 | | 0 | 1 | 2 | 3 | 4 | | 1 | 5 | 6 | 7 | 8 | | 2 | 9 | 10 | 11 | 12 | | 3 | 13 | 14 | 15 | 16 | | 4 | 17 | 18 | 19 | 20 | | 5 | 21 | 22 | 23 | 24 | | 6 | 25 | 26 | 27 | 28 | | 7 | 29 | 30 | 31 | 32 | | 8 | 33 | 34 | 35 | 36 | | 9 | 37 | 38 | 39 | 40 |
Auf dem Chart ist zu erkennen, dass die Spaltenüberschriften und Tabellenzeilen aktiv sind und darauf reagieren, wenn der Mauszeiger darüber bewegt wird. Die Verarbeitung der Benutzerinteraktion mit der Tabelle wird im nächsten Artikel behandelt.
Fazit
Wir haben gelernt, wie man einfache Tabellen erstellt und diese auf einem Chart darstellt. Bislang handelt es sich jedoch nur um eine statische Tabelle, in der die einmal empfangenen Daten angezeigt werden. Im nächsten Artikel geht es um Tabellenanimationen – das Ändern und Anzeigen dynamischer Daten sowie die Interaktion mit dem Benutzer, um die Darstellung von Zeilen und Spalten in einer Tabelle anzupassen. Außerdem werden wir im nächsten Artikel eine noch einfachere Methode zur Erstellung von Tabellen implementieren.
In diesem Artikel verwendete Programme:
| # | Name | Typ | Beschreibung |
|---|---|---|---|
| 1 | Tables.mqh | Klassenbibliothek | Klassen zum Erstellen eines Tabellenmodells |
| 2 | Base.mqh | Klassenbibliothek | Klassen zum Erstellen eines Basisobjekts für Steuerelemente |
| 3 | Controls.mqh | Klassenbibliothek | Klassen für Steuerelemente |
| 4 | iTestTable.mq5 | Testindikator | Indikator zum Testen von Manipulationen am TableView-Steuerelement |
| 5 | MQL5.zip | Archiv | Ein Archiv der oben genannten Dateien zum Entpacken in das MQL5-Verzeichnis des Client-Terminals |
Alle erstellten Dateien sind dem Artikel zum Selbststudium beigefügt. Die Archivdatei kann in den Terminalordner entpackt werden; dabei werden alle Dateien im vorgesehenen Ordner abgelegt: \MQL5\Indicators\Tables\.
Übersetzt aus dem Russischen von MetaQuotes Ltd.
Originalartikel: /ru/articles/19288
Warnung: Alle Rechte sind von MetaQuotes Ltd. vorbehalten. Kopieren oder Vervielfältigen untersagt.
Dieser Artikel wurde von einem Nutzer der Website verfasst und gibt dessen persönliche Meinung wieder. MetaQuotes Ltd übernimmt keine Verantwortung für die Richtigkeit der dargestellten Informationen oder für Folgen, die sich aus der Anwendung der beschriebenen Lösungen, Strategien oder Empfehlungen ergeben.
Eine hervorragende Erläuterung des MVC-Modells, aber wie genau trägt diese Komplexität zur Verbesserung des Handels bei – denn darum geht es uns hier ja eigentlich?
Sind alle anderen Herausforderungen im Handel bereits gelöst, sodass nur noch die Benutzeroberfläche übrig bleibt?
Manchmal vergessen wir, wozu ein Tool eigentlich dient – oder sind frustriert, wenn es nicht so funktioniert, wie wir es uns wünschen – und versuchen am Ende, es zu Dingen zu zwingen, für die es nie gedacht war und die es niemals leisten wird
Eine hervorragende Beschreibung von MVC, aber wie genau trägt diese Komplexität zur Verbesserung des Handels bei, um den es uns hier eigentlich geht?
Sind etwa alle anderen Probleme des Handels gelöst, sodass nur noch die Benutzeroberfläche übrig bleibt?
Manchmal vergessen wir, wozu ein Tool eigentlich dient, oder sind frustriert, wenn es nicht so funktioniert, wie wir es wollen, und versuchen schließlich, es dazu zu zwingen, etwas zu tun, wofür es nie gedacht war und was es niemals tun wird.