MQL5におけるMVCパラダイムに基づくテーブル:モデルコンポーネントをビューコンポーネントに統合する
目次
- はじめに
- ライブラリクラスの改良
- テーブルセルクラス(ビュー)
- テーブル行クラス(ビュー)
- テーブルの列ヘッダクラス(ビュー)
- テーブルヘッダクラス(ビュー)
- テーブルクラス(ビュー)
- 結果の検証
- 結論
はじめに
記事「MQL5のテーブルモデルに基づくテーブルクラスとヘッダクラス:MVC概念の適用」では、テーブルモデルクラスの作成を完了しました(MVC概念において、これはモデルコンポーネントに相当します)。 続いて、用途や複雑さが大きく異なるコントロールの基盤となる、シンプルなコントロールのライブラリの開発を進めてきました。 特に、TableViewコントロールを作成するためのビューコンポーネントです。
この記事では、モデルコンポーネントとビューコンポーネント間の連携の実装について解説します。 つまり、今回は表形式のデータとその視覚的な表現を、1つのコントロールに統合します。
このコントロールは、パネルオブジェクトクラスに基づいて作成され、次の要素で構成されます。
- ベースパネル: テーブルヘッダとテーブルのデータ領域を配置するための土台となるパネルです。
- テーブルヘッダ: 複数の列ヘッダで構成されるパネルです。各列ヘッダは、CButtonクラスを基に作成されます。
- コンテナ: 表形式のデータを格納し、コンテンツのスクロールを可能にするコンテナです。
- 行配置用パネル: テーブル行を配置するためのパネルです。このパネルは項目3のコンテナに取り付けられ、コンテナの表示領域を超えた部分は、コンテナのスクロールバーを使ってスクロールできます。
- テーブル行: テーブルセルを描画するためのパネルです。項目4の行配置用パネルに取り付けられます。 このオブジェクトは、テーブルの行数と同じ数だけ作成されます。
- テーブルセルクラスは、指定されたキャンバス(CCanvas)上の指定座標に描画できる新しいクラスです。 このクラスのオブジェクトはテーブル行オブジェクト(項目5)に取り付けられ、テーブル行オブジェクトのキャンバスが描画要素として指定されます。そして、このパネル上の指定座標にテーブルセルが描画されます。 各テーブルセルの領域は、テーブル行オブジェクト(項目5)内でCBoundクラスのインスタンスによって設定され、テーブルセルクラスのオブジェクトはこのインスタンスに取り付けられます。
テーブルの行とセルを構築するこのアルゴリズムでは、各行を水平方向に複数の領域に分割し、それぞれにセルクラスのオブジェクトを取り付けます。これにより、セルを行内の目的の領域に再割り当てするだけで、セルの並べ替えや位置変更を簡単におこなうことができます。
以上のことから、コントロールへのポインタを受け取り、そのコントロールのキャンバス上に描画する新しいオブジェクトクラスが必要だと分かります。 現在、すべてのライブラリオブジェクトは、new演算子によって生成される際、独自のキャンバスオブジェクト(背景および前景)を作成します。 しかし、ここで必要なのは、自身のサイズを設定・取得でき、さらに描画先のコントロールへのポインタを設定できるオブジェクトです。
CBoundクラスは、作成されたオブジェクトの寸法を設定・取得する機能を備えており、すべてのコントロールの基底オブジェクトに組み込まれています。 背景と前景のキャンバスは、そのオブジェクト内で作成されます。 つまり、基底クラスを継承し、寸法の設定・取得に使用するCBoundクラスを含む、別の中間オブジェクトを作成する必要があります。 CCanvasオブジェクトが作成されるクラスは、このオブジェクトを継承することになります。 こうして、この中間クラスを継承して、描画先のコントロールへのポインタを受け取るクラスを作成できます。
作成済みのクラスのファイルを仕上げてから、新しいクラスを記述しましょう。
ライブラリクラスの改良
開発中のライブラリのすべてのファイルは、\MQL5\Indicators\Tables\Controls\にあります。 まだこれらのファイルをお持ちでない場合は、前回の記事から全ファイルの以前のバージョンを入手できます。 また、このプロジェクトにはテーブルクラスのファイル(モデルコンポーネント)も必要です。このファイルは、開発を完了した際の記事から入手できます。 Tables.mqhは、\MQL5\Indicators\Tables\に保存する必要があります。 Base.mqhファイルとControl.mqhファイルを改良します。
Tables.mqhファイルの冒頭、マクロセクションに、ファイルIDを記述します。
//+------------------------------------------------------------------+ //| 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
これは、2つの異なるインクルードファイルを個別にコンパイルできるように、それぞれのファイルでMARKER_START_DATAマクロ置換を宣言するために必要です。
Base.mqhファイルを開きます。テーブルモデルのクラスファイルをインクルードし、新しいクラスの前方宣言を追加します。
//+------------------------------------------------------------------+ //| 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 | //+------------------------------------------------------------------+
マクロ置換セクションで、MARKER_START_DATAマクロの宣言を その定義の有無を確認する条件付きコンパイルの指示で囲みます。
//+------------------------------------------------------------------+ //| 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
これで、2つの異なるファイルで同じマクロ置換を宣言しても、各ファイルを個別にコンパイルする場合も、両方をまとめてコンパイルする場合も、コンパイルエラーは発生しなくなります。
UI要素の型の列挙に新しい型を追加し、アクティブな要素の型の最大値を新たに設定します。
//+------------------------------------------------------------------+ //| 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
要素の型ごとの短縮名を返す関数に、新しい戻り値を追加します。
//+------------------------------------------------------------------+ //| 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 } }
新しいクラスでオーバーライドする必要があるため、UI要素の基底クラスで識別子の設定メソッドを仮想メソッドにします。
//+------------------------------------------------------------------+ //| 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) {} };
各オブジェクトは、その構成要素として、コントロールのサイズを返す矩形領域クラスCBoundのオブジェクトを持っています。 また、各コントロールには、CBoundオブジェクトのリストがあります。 このリストには多数のCBoundオブジェクトを格納でき、それらを使ってUI要素の表面上にさまざまな領域を指定できます。
こうした各領域は、さまざまな用途に利用できます。 たとえば、UI要素内に特定の領域を定義し、その領域内のカーソルの位置を追跡して、マウスカーソルによるその領域への操作に応じて反応させることができます。 特定のコントロールは、特定の領域内に配置することで、その領域内に表示させることができます。 これをおこなうには、コントロールへのポインタをCBoundオブジェクトに書き込めるようにする必要があります。
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); } };
現在、CBound矩形領域オブジェクトはCCanvasBaseクラス内で宣言されており、このクラスではUI要素の背景と前景を描画するための2つのCCanvasオブジェクトが作成されています。 つまり、すべてのUI要素には、内部に2つのキャンバスが含まれているということです。 しかし、ここで作成したいのは、描画先のキャンバスを持つコントロールを指定できるクラスです。 同時に、独自のキャンバスを作成せず、グラフィック要素を作成するという全体的なコンセプトからも逸脱しないようにします。
つまり、CBoundクラスのオブジェクトを CCanvasBaseクラスから、キャンバスオブジェクトを作成しない別の親クラスへ移し、CCanvasBaseクラスがその親クラスを継承するようにします。 また、CCanvasBaseクラスでは、2つのCCanvasのインスタンスを宣言するのではなく、作成されるキャンバスへのポインタを宣言し、2つのキャンバスオブジェクトを作成するメソッドを実装します。 また、グラフィック要素が背景および前景のキャンバスオブジェクトを管理するかどうかを示すフラグを宣言します。 これは、作成されたキャンバスオブジェクトの削除を管理するために必要です。
Base.mqhファイル内で、CAutoRepeatクラスの直後、CCanvasBaseクラスの前に、CBaseObjを継承した新しいCBoundedObjクラスを実装し、CCanvasBaseクラスからCBoundオブジェクトを扱うすべてのメソッドをそのままこのクラスに移し替えます。
//+------------------------------------------------------------------+ //| 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); }
ここで示すクラスは、基底クラスであるCBaseObjのプロパティをそのまま継承し、オブジェクトの境界(CBoundクラス)を指定できるようにしたもので、キャンバス管理フラグを備えています。
グラフィック要素のキャンバスの基底クラスは、従来のCBaseObjクラスではなく、新しいCBoundedObjクラスを継承するようにします。 また、CBoundクラスのオブジェクトを使って要素のサイズを設定・取得するための処理はすべて、すでに新しいCBoundedObjクラスに移され、CCanvasBaseクラスからは削除されています。 現在、キャンバスオブジェクトはクラスのインスタンスとして宣言されるのではなく、生成されるCCanvasオブジェクトへのポインタとして宣言されています。
//+------------------------------------------------------------------+ //| 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
キャンバスのグラフィックオブジェクトの座標とサイズを取得するメソッドはpublicとして公開し、キャンバスのサイズを変更するメソッドは仮想メソッドとして実装します。
//--- 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)); }
キャンバスを作成するメソッドを、クラスのprotectedセクションで宣言します。
//--- 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; }
コンテナの境界で要素をクリッピングすることを許可するフラグを設定するメソッドは、仮想メソッドとして実装します。
//--- 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; }
クラスのコンストラクタでは、背景および前景用のキャンバスオブジェクトを作成するメソッドを呼び出すようにします。
//+------------------------------------------------------------------+ //| 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(); } }
以下は、背景と前景用のキャンバスを作成するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
オブジェクトを破棄するメソッドでは、キャンバス管理フラグを確認するようにします。
//+------------------------------------------------------------------+ //| 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; } }
オブジェクトがキャンバスを管理している場合にのみ、キャンバスは削除されます。 描画用として別のコントロールのキャンバスがオブジェクトに渡された場合、そのオブジェクトはキャンバスを削除しません。キャンバスを削除するのは、その所有元のオブジェクトだけでなければなりません。
クラスのデフォルトの初期化メソッドでは、オブジェクトに対してキャンバス管理フラグが設定されます。
//+------------------------------------------------------------------+ //| 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; }
独自のキャンバスを持たず、CBoundedObjクラスを継承するオブジェクトだけは、このフラグを false にリセットする必要があります。
次に、Controls.mqhファイルを開き、改良を加えます。
マクロ置換のセクションに、テーブル行とテーブルヘッダのデフォルトの高さを定義する2つの新しいマクロ置換を実装します。
//+------------------------------------------------------------------+ //| 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
このファイルには、グラフィカル要素のリストを格納するための、CListObjオブジェクトの連結リストクラスが含まれています。 テーブルモデルクラスのファイルから、このファイルにコピーしました。 クラス名を同じままにすると、名前の競合が発生します。また、異なるファイルにあるこれら2つのリストに格納されるオブジェクトは、そもそもまったく異なります。 そこで、クラス自体は変更せずに、名前だけを変更します。 これは、UI要素の連結リストを表すクラスになります。
//+------------------------------------------------------------------+ //| 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); };
ファイル全体で、文字列「CListObj」を文字列「CListElm」に置き換えます。
リスト項目を作成するメソッドに、新しい種類のUI要素を追加します。
//+------------------------------------------------------------------+ //| 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; } }
UI要素の基底クラスに、オブジェクトへのポインタを返すメソッドを追加します。
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; }
テキストラベルクラスで、キャンバス上にテキストを表示するメソッドを仮想メソッドにします。
//--- 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);
CPanel パネルクラスにおいて、サイズ変更メソッドを改良します。
//+------------------------------------------------------------------+ //| 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; }
メソッドの改良の要点は、要素がコンテナ内にある場合、または要素のサイズが変更された場合に、コンテナに対して要素の新しいサイズを確認する必要があるということです。 要素がコンテナの境界を超える大きさになった場合、その要素はコンテナのサイズに合わせてクリッピングされます(これはすでに実装済みです)が、その場合でもコンテナにスクロールバーを表示する必要があります。 UI要素のサイズを変更するメソッドに、コンテナオブジェクトのメソッドであるCheckElementSizes()を使用して、このチェック機能を追加しました。
CPanelクラスでパネルオブジェクトの外観を描画するメソッドでは、境界線を描画する条件を、4辺のうち少なくとも1辺の BorderWidth パラメータの値が0以外である場合に限定します。
//+------------------------------------------------------------------+ //| 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); }
パネルオブジェクトクラスで、新しい要素を作成してリストに追加するメソッドに、新しいコントロールの作成処理を追加します。
//+------------------------------------------------------------------+ //| 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; }
オブジェクトを前景に配置するメソッドに、コンテナのサイズに合わせて、取り付けられたオブジェクトをクリッピングする処理を追加します。
//+------------------------------------------------------------------+ //| 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); }
水平スクロールバーのクラスには、要素をコンテナの境界に合わせてクリッピングできることを示すフラグがあります。 スクロールバーオブジェクトは複数のオブジェクトで構成されており、それぞれのオブジェクトに対して同じフラグ値を設定する必要があります。 すべてを1つのメソッドで処理しましょう。クラス内で、コンテナの境界でのクリッピングを指定するフラグを設定するメソッドを再定義します。
//+------------------------------------------------------------------+ //| 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) {} };
メソッドの実装:
//+------------------------------------------------------------------+ //| 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); }
このメソッドに渡されたフラグは、スクロールバーを構成する各オブジェクトに対して設定されます。
オブジェクトの初期化メソッドでは、コンテナの境界でのクリッピングを指定するフラグを各要素に設定する必要はなくなりました。 メソッドの最後に SetTrimmered()メソッドを呼び出せば十分です。
//+------------------------------------------------------------------+ //| 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); }
垂直スクロールバーのクラスに対しても、まったく同じ改良が施されています。 これらは前述の内容と完全に同一であるため、ここでは繰り返しません。
コンテナオブジェクトのクラスで、CheckElementSizesメソッドをpublicにします。
//+------------------------------------------------------------------+ //| 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()); }
このメソッドは、コンテナにバインドされた要素から呼び出されるため、アクセスできるように public にする必要があります。
ライブラリクラスの主な改良点について確認しました。 いくつかの軽微な改善や修正は、今回の対象範囲から除外されています。 記事に添付されているファイルで、コードの全文をご覧ください。
テーブルモデルは、テーブルセル、テーブル行、および最終的にテーブルを構成するテーブル行のリストから成ります。 上記に加え、テーブルには、列ヘッダで構成されるテーブルヘッダもあります。
- テーブルセルは、行番号、列番号、および内容を格納する独立した要素です。
- テーブル行は、固有の番号を持つテーブルセルのリストです。
- テーブルはテーブル行のリストであり、列ヘッダのリストを表すテーブルヘッダを持つことができます。
ビューコンポーネントも、テーブルモデルのデータを表示するために、ほぼ同じ構造を持つことになります。 テーブルオブジェクトは、例えば、データの配列と、そのデータのヘッダの配列に基づいて作成されます。 次に、テーブルモデル(モデルコンポーネント)へのポインタを、作成したテーブルの視覚表示オブジェクト(ビューコンポーネント)に渡すと、すべてのデータがテーブルセルに書き込まれます。
このマイルストーンでは、マウスカーソルによる表示制御機能のない、単純な静的テーブルが作成されます。
テーブルセルクラス(ビュー)
テーブルは、テーブル行のリストで構成されています。 各テーブル行は、背景と前景を描画するための2つのキャンバスを備えたオブジェクトで構成されています。 テーブルセルは、各テーブル行に横一列に並んでいます。 セルごとに専用のキャンバスを持たせる意味はありません。 各テーブル行を領域に「分割」するだけでよく、各領域がそれぞれのセルの配置場所に対応します。 そして、テーブル行オブジェクトのキャンバスにセルのデータを描画します。
こうした目的のために、最初の段階で中間クラスを作成したのです。 このクラスが保持するのは、オブジェクトのサイズと座標、および描画先のキャンバスを持つコントロールへのポインタだけです。 そして、このようなオブジェクトがテーブルセルになります。 テーブル行オブジェクトのキャンバスに描画するために、そのオブジェクトへのポインタを渡します。
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){} };
ここにある変数とメソッドにはすべて、コード内でコメントが付けられています。 ここでは、セルのインデックスとその識別子は同じものです。 そのため、仮想メソッドSetID()をオーバーライドし、インデックスと識別子に同じ値を設定するようにしています。 宣言されたメソッドの実装について見てみましょう。
クラスのコンストラクタでは、オブジェクトの初期化メソッドが呼び出され、セルの識別子とその名前が設定されます。
//+------------------------------------------------------------------------+ //| 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); }
以下は、クラスオブジェクトの初期化メソッドです。
//+------------------------------------------------------------------+ //| 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; }
必ずそのオブジェクトがキャンバスを管理しないことを示すフラグを設定します。これにより、そのオブジェクトが破棄された際に、他のオブジェクトのキャンバスが削除されるのを防げます。
以下は、オブジェクトの説明を返すメソッドです。
//+------------------------------------------------------------------+ //| 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()); }
このメソッドは、オブジェクト型の名前、識別子、座標、およびセルサイズを記載した行をログに出力します。
以下は、テーブル行と背景および前景のキャンバスをセルに割り当てるメソッドです。
//+---------------------------------------------------------------------+ //| 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(); }
テーブル行オブジェクトへのポインタがメソッドに渡されます(クラスの説明は後述)。そのポインタが無効な場合は、その旨を報告してNULLを返します。 次に、テーブル行へのポインタをクラス変数に格納し、そのテーブル行オブジェクトから取得した背景および前景のキャンバスへのポインタと描画オブジェクトへのポインタもクラス変数に格納します。
テーブルモデルオブジェクトにも、独自の行とセルがあります。 このクラスにはテーブルセルモデルが割り当てられ、このクラスはセルモデルのデータを行オブジェクトのキャンバス上に描画します。
以下は、セルモデルを割り当てるメソッドです。
//+------------------------------------------------------------------+ //| 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; }
まず、渡されたセルモデルへのポインタが有効かどうかを確認し、次に、テーブル行がすでにこのセルオブジェクトに割り当てられているかを確認します。 いずれかの条件が満たされない場合は、その旨をログに記録し、falseを返します。 次に、セルモデルへのポインタを変数に格納し、対応する行上のセル領域の座標と寸法を設定します。
テーブルの行や列を並べ替える際は、セルオブジェクトへのポインタを再割り当てするだけで、テーブル内の正確な座標を持つこのオブジェクトが、新たに割り当てられたセルのデータを描画します。
以下は、アンカーポイントに応じてテキストのX座標とY座標を返すメソッドです。
//+------------------------------------------------------------------+ //| 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; }
変数を参照渡しでメソッドに渡し、出力テキストの左上隅について計算した座標をそれらの変数に格納します。 セルのテキストサイズの取得に失敗した場合、このメソッドはfalseを返します。
左上隅の座標を計算した後、計算したテキストの座標を変数に格納し、trueを返します。
以下は、テキストのアンカーポイントを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
まず、新しいアンカーポイントを変数に格納します。次に、このセルの再描画フラグが設定されている場合は、指定されたチャート再描画フラグを渡して、セルの描画メソッドを呼び出します。
以下は、アンカーポイントとテキストのオフセットを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドでは、アンカーポイントに加えて、X軸およびY軸方向のテキストの初期オフセットも設定します。
以下は、オブジェクトを色で塗りつぶすメソッドです。
//+------------------------------------------------------------------+ //| 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); }
矩形領域の四隅の正しい座標を求めます。 次に、背景をテーブル行の背景色で塗りつぶし、前景を透明色で塗りつぶします。
以下は、変更を表示に反映するためにオブジェクトを更新するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
背景と前景のキャンバスが有効な場合、指定されたチャート再描画フラグを引数として、それぞれの更新メソッドが呼び出されます。
以下は、セルビューを描画するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドのロジックはコメントで説明されています。 オブジェクトがコンテナの境界でクリッピングされる場合は、座標の補正が必要です。 この場合、初期座標はキャンバスのグラフィックオブジェクトの実際の座標からではなく、コンテナの境界の外側に仮想的に位置するグラフィック要素の座標から計算されます。
区切り線は、セルの右側のみに引かれます。 また、右端のセルでない場合は、コンテナによって表示範囲が制限されるため、そこに追加の線を描画する必要はありません。
以下は、セルのテキストを表示するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドのロジックは、コード内のコメントで詳しく説明されています。 表示するテキストがセル領域からはみ出す場合は、領域の境界でクリッピングされ、末尾が省略記号(「...」)に置き換えられます。これは、テキスト全体がセルの幅に収まらないことを示します。
以下は、割り当てられたテーブル行モデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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(); }
このメソッドを使用すると、モデルコンポーネントのどのセルがビューコンポーネントのセルに割り当てられているかを確認できます。
以下は、ファイルを操作するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
これらのメソッドを使用すると、テーブルセルのデータをファイルに保存したり、ファイルから読み込んだりできます。
それでは、テーブル行の視覚的な表現を担うクラスについて見ていきましょう。
テーブル行クラス(ビュー)
テーブル行は、パネルクラスを継承したオブジェクトです。 CTableCellViewクラスのセルオブジェクトのリストを保持します。
引き続き、Controls.mqhファイルにコードを記述します。
//+------------------------------------------------------------------+ //| 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){} };
テーブル行にもセルと同じ特徴があり、行インデックスプロパティの値はその識別子と等しくなります。 ここでも、識別子を設定する仮想メソッドがオーバーライドされており、インデックスと識別子の両方のプロパティを同時に設定します。
クラスのコンストラクタでは、オブジェクトの初期化メソッドが呼び出されます。
//+----------------------------------------------------------------------+ //| 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(); }
オブジェクトの初期化:
//+------------------------------------------------------------------+ //| CTableRowView::Initialization | //+------------------------------------------------------------------+ void CTableRowView::Init(void) { //--- Initialize the parent object CPanel::Init(); //--- background - opaque this.SetAlphaBG(255); //--- Border width this.SetBorderWidth(1); }
以下は、オブジェクトのデフォルト色を初期化するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
以下は、新しいセルビューオブジェクトを実装し、リストに追加するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
各セルをテーブル行オブジェクト内の専用領域に割り当てるだけでなく、new演算子で作成したオブジェクトをリストに格納しておく必要があります。そうしない場合は、自分でそれらを管理し、必要に応じて削除しなければなりません。
それらをリストに格納した方が簡単です。そうすれば、ターミナルサブシステム自体が、いつ削除すべきかを管理してくれます。 このメソッドは、新しいセルビューオブジェクトを作成し、テーブル行のセルリストに追加します。 オブジェクトの作成後、そのオブジェクトが属するテーブル行と、テーブルセルのモデルデータを描画するキャンバスが設定されます。
以下は、テーブル行モデルを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
テーブル行モデルへのポインタがメソッドに渡され、モデル内のセル数だけループを繰り返して、セルビューオブジェクト用の新しい領域とセル自体(CTableCellViewクラス)を作成します。 そして、新しく作成した各セルを、それぞれの新しい領域に割り当てます。 最終的に、対応するテーブルセルへのポインタが割り当てられたセル領域のリストが得られます。
以下は、テーブル行のビューを描画するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
まず、テーブル行を背景色で塗りつぶし、下端に線を引きます。 次に、テーブル行のセル領域をループで順に取得し、各領域からセルオブジェクトへのポインタを取得して、その描画メソッドを呼び出します。
以下は、割り当てられたテーブル行モデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドを使用すると、このテーブル行のビューにどの行モデルが割り当てられているかを確認できます。
以下は、ファイルを操作するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
これらのメソッドを使用すると、テーブル行のデータをファイルに保存したり、ファイルから読み込んだりできます。
各テーブルにはヘッダが必要です。 これにより、テーブルの各列にどのようなデータが表示されているかを把握することができます。 テーブルヘッダは、列ヘッダのリストです。 テーブルの各列には、その列に含まれるデータの種類と名前を表示する列ヘッダがあります。
テーブルの列ヘッダクラス(ビュー)
テーブルの列ヘッダは、「Button」オブジェクト(CButton)から派生した独立したオブジェクトであり、その動作を継承し、拡張します。 現在の実装では、ボタンのプロパティは追加されません。単に、各状態に応じて色を変更するだけです。 次の記事では、ヘッダに並べ替えの方向を示す表示として、ボタン領域の右側に上向き/下向きの矢印を追加し、ボタンのクリックで並べ替えを開始するイベントモデルも追加します。
引き続き、Controls.mqhファイルにコードを記述します。
//+------------------------------------------------------------------+ //| 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){} };
このメソッドのインデックスは、前述の2つのクラスの場合と同様に、識別子と同じ値になります。 また、識別子を設定するメソッドも、前述のクラスと同様です。
クラスのコンストラクタでは、オブジェクトの初期化メソッドが呼び出され、識別子に初期値として0が設定されます(オブジェクトの作成後に変更される)。
//+------------------------------------------------------------------+ //| 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); }
以下は、オブジェクトの初期化メソッドです。
//+------------------------------------------------------------------+ //| 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(); }
以下は、オブジェクトのデフォルト色を初期化するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
以下は、列ヘッダビューを描画するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
まず、背景を指定された色で塗りつぶし、次に左側に明るい縦線、右側に暗い縦線を描画します。 次に、前景のキャンバスにタイトルテキストが表示されます。
以下は、オブジェクトの説明を返すメソッドです。
//+------------------------------------------------------------------+ //| 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()); }
このメソッドは、オブジェクトのID、座標、寸法を含む要素タイプの説明を返します。
以下は、列ヘッダモデルを割り当てるメソッドです。
//+------------------------------------------------------------------+ //| 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; }
列ヘッダモデルへのポインタがメソッドに渡され、そのポインタは変数に格納されます。 次に、描画オブジェクトに対して、描画領域の座標と寸法を設定します。
以下は、割り当てられた列ヘッダモデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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(); }
ヘッダの視覚的表現オブジェクトに割り当てられた列ヘッダモデルの説明をログに出力することで、その内容を確認することができます。
以下は、ファイルを操作するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
ヘッダのパラメータをファイルに保存し、ファイルから読み込む機能を提供します。
テーブルヘッダクラス(ビュー)
テーブルヘッダは、パネルコントロール(CPanel)をベースとする、列ヘッダオブジェクトの単純なリストです。 その結果、このようなオブジェクトは、テーブルの列を管理するためのツールを提供します。
この実装では、通常の静的オブジェクトとなります。 ユーザーとのやり取りに関する機能はすべて、後日追加される予定です。
引き続き、同じファイルにコードを記述します。
//+------------------------------------------------------------------+ //| 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){} };
オブジェクトにテーブルヘッダモデルが割り当てられ、その内容に基づいて列ヘッダオブジェクトが作成され、関連付けられた要素のリストに追加されます。
クラスのコンストラクタでは、オブジェクトの初期化メソッドが呼び出されます。
//+------------------------------------------------------------------+ //| 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(); }
以下は、オブジェクトの初期化メソッドです。
//+------------------------------------------------------------------+ //| CTableHeaderView::Initialization | //+------------------------------------------------------------------+ void CTableHeaderView::Init(void) { //--- Initialize the parent object CPanel::Init(); //--- Background color - opaque this.SetAlphaBG(255); //--- Border width this.SetBorderWidth(1); }
以下は、オブジェクトのデフォルト色を初期化するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
以下は、新しい列ヘッダの表示オブジェクトを作成してリストに追加するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
列ヘッダオブジェクトは、ライブラリオブジェクト用の標準メソッド InsertNewElement() を使用して作成されます。このメソッドは、作成したオブジェクトを、その親オブジェクトの UI 要素リストに追加します。
以下は、ヘッダモデルを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
テーブルヘッダモデルがメソッドに渡されます。 モデル内の列ヘッダの数だけループを繰り返し、各反復で列ヘッダを配置する領域を新たに作成します。 列ヘッダオブジェクトを作成し、それを現在の領域に割り当てます。 ループ終了時には、列ヘッダが割り当てられた領域のリストが得られます。
以下は、テーブルヘッダのビューを描画するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
まず、テーブルヘッダの領域全体を背景色で塗りつぶし、次に下端に区切り線を描画します。 次に、ループ内でヘッダ領域のリストを順にたどり、次の領域を取得します。 そして、この領域から、この領域に割り当てられている列ヘッダオブジェクトを取得します。 このオブジェクトの描画メソッドを呼び出します。
以下は、割り当てられたテーブルヘッダモデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このオブジェクトに割り当てられたテーブルヘッダモデルをログに出力できるようにします。
テーブルの視覚的表現は、モデルからテーブルとヘッダに関するデータを受け取り、そのデータをさまざまなコントロール上に描画する複合オブジェクトです。 これは、ヘッダと、表形式のデータ(テーブル行)を含むコンテナを備えたパネルです。
テーブルクラス(ビュー)
引き続き、Controls.mqhファイルにコードを記述します。
//+------------------------------------------------------------------+ //| 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){} };
このクラスは、パネルオブジェクトクラスを継承しています。 3つのモデルコンポーネントと3つのビューコンポーネントが表示されています。 このクラスには、テーブルモデル、ヘッダモデル、およびテーブルへのポインタが含まれています。 このテーブルから、表データとヘッダへのポインタを取得します。 また、ヘッダ、テーブル行パネル、およびこのパネルを配置するためのコンテナへのポインタが3つあります。
つまり、テーブル行はパネルオブジェクトにアタッチされ(複数の要素をアタッチ可能)、このパネルはコンテナにアタッチされます(要素を1つだけアタッチ可能)。コンテナにはスクロールバーがあり、テーブル行を含むパネルを移動できます。 このように、見た目としては、テーブルヘッダの下にスクロール可能なテーブル(セルで構成された行と列)が配置された要素になります。
クラスのコンストラクタ内で、オブジェクトの初期化メソッドを呼び出します。
//+------------------------------------------------------------------+ //| 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(); }
初期化メソッド内で、オブジェクトのパネル上に必要なすべてのコントロールを作成します。
//+------------------------------------------------------------------+ //| 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); }
以下は、テーブルモデルを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
テーブルモデルオブジェクトへのポインタをメソッドに渡すだけで、それを変数に格納し、その変数からオブジェクトにアクセスします。
以下は、テーブルヘッダモデルを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
テーブルヘッダのモデルオブジェクトへのポインタをメソッドに渡して、後でアクセスするための変数に代入します。
以下は、テーブルオブジェクトを設定するメソッドです。
//+------------------------------------------------------------------+ //| 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; }
テーブルオブジェクトへのポインタがメソッドに渡されます。 このオブジェクトからヘッダモデルとテーブルモデルを取得し、対応する変数に代入します。 次に、ヘッダモデルとテーブルモデルのデータを使用して、ヘッダとテーブルを視覚的に表現するためのオブジェクトを作成します。
以下は、モデルからテーブルオブジェクトを作成するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドのロジックは、コード内のコメントで説明されています。 テーブルモデルの行数分だけループを繰り返し、新しいテーブル行オブジェクトを作成してパネルに追加すると同時に、パネルの最終的な高さを計算します。 ループを完了し、必要なテーブル行をすべて作成した後、ループ内で算出されたサイズに基づいてパネルの高さが調整されます。
以下は、テーブルビューを描画するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
まずテーブルヘッダを描画し、その下にコンテナ内のテーブル行を描画します。
以下は、割り当てられたテーブルモデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
これにより、割り当てられたテーブルモデルをログに出力することができます。
以下は、割り当てられたテーブルヘッダモデルをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
これにより、割り当てられたテーブルヘッダモデルをログに出力することができます。
以下は、割り当てられたテーブルオブジェクトをログに出力するメソッドです。
//+------------------------------------------------------------------+ //| 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); }
このメソッドは、オブジェクトに割り当てられたテーブル全体を、ヘッダとデータを含めてログに出力します。
これで、テーブルモデルの視覚的表現を作成するためのすべてのクラスの実装が完了しました。 それでは、データの配列から簡単なテーブルを作成する方法を見てみましょう。
結果の検証
ターミナルのディレクトリ \MQL5\Indicators\Tables\ 内に、バッファを持たず、チャートサブウィンドウに表示される新しいインジケータを作成します。
//+------------------------------------------------------------------+ //| 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
ライブラリをインジケータファイルに組み込み、オブジェクトへのポインタをグローバルに宣言します。
//+------------------------------------------------------------------+ //| 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)
続いて、インジケータのOnInit()ハンドラに以下のコードを記述します。
//+------------------------------------------------------------------+ //| 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); }
このコードは、次の3つのブロックで構成されています。
- テーブルを構築するためのパネルを作成する
- テーブルとヘッダの2つの配列に表形式のデータを作成する(モデルコンポーネント)
- パネル内にテーブルを作成する(ビューコンポーネント)
実際、テーブルを作成するには2つの手順が必要です。つまり、データを構築すること(項目2)と、テーブルを構築すること(項目3)です。 このパネルは、装飾用およびグラフィック要素の土台としてのみ必要とされます。
インジケータの残りのコードを追加します。
//+------------------------------------------------------------------+ //| 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(); }
インジケータをコンパイルし、チャート上で実行します。

ターミナルログには、テーブルの作成に成功した旨のメッセージ、テーブルの説明、およびヘッダ付きのテーブルが表示されます。
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 |
チャート上では、列ヘッダとテーブル行がアクティブになっており、マウスポインタを重ねると反応することがわかります。 テーブルとユーザーとのやり取りの処理については、次回の記事で取り上げます。
結論
単純なテーブルを作成し、チャート上に表示する方法を学びました。 しかし、現時点では、これは一度受け取ったデータを表示するだけの静的なテーブルに過ぎません。 次の記事では、テーブルのアニメーション、つまり動的なデータの変更や表示、およびユーザーとの対話を通じてテーブル行や列の表示をカスタマイズする方法について取り上げます。 また、次の記事では、テーブルの作成をさらに簡単にする方法を実装していきます。
本記事で使用したプログラム
| # | 名前 | 種類 | 説明 |
|---|---|---|---|
| 1 | Tables.mqh | クラスライブラリ | テーブルモデルを作成するためのクラス |
| 2 | Base.mqh | クラスライブラリ | コントロールのベースオブジェクトを作成するためのクラス |
| 3 | Controls.mqh | クラスライブラリ | コントロールのクラス |
| 4 | iTestTable.mq5 | テスト用インジケータ | TableViewコントロールの操作をテストするためのインジケータ |
| 5 | MQL5.zip | アーカイブ | クライアントターミナルのMQL5ディレクトリに展開するための、上記ファイルのアーカイブ |
作成したすべてのファイルは、自習用に記事に添付されています。 アーカイブファイルをターミナルフォルダに解凍すると、すべてのファイルが指定されたフォルダ(\MQL5\Indicators\Tables\)に配置されます。
MetaQuotes Ltdによってロシア語から翻訳されました。
元の記事: /ru/articles/19288
警告: これらの資料についてのすべての権利はMetaQuotes Ltd.が保有しています。これらの資料の全部または一部の複製や再プリントは禁じられています。
この記事はサイトのユーザーによって執筆されたものであり、著者の個人的な見解を反映しています。MetaQuotes Ltdは、提示された情報の正確性や、記載されているソリューション、戦略、または推奨事項の使用によって生じたいかなる結果についても責任を負いません。
MVCの解説は素晴らしいですが、この複雑さが、私たちが本当に求めている「取引」を具体的にどのように改善するのでしょうか?
他のすべての取引上の課題は解決され、残っているのはユーザーインターフェースだけなのでしょうか?
私たちは、ツールが本来何のためにあるのかを忘れてしまったり、思い通りに動かないことに苛立ちを感じたりして、結局、そのツールが本来意図されていないこと、そして決して実現できないことをさせようとしてしまうことがあります。
MVCについての素晴らしい解説ですが、この複雑さが、そもそも私たちがここに集まった目的である取引を、具体的にどのように改善するのでしょうか?
まさか、取引に関する他の問題はすべて解決され、残っているのはユーザーインターフェースだけなのでしょうか?
私たちは時々、そのツールが本来何のために必要なのかを忘れてしまったり、思い通りに動作しないことに苛立ちを感じたりして、結局、そのツールが本来意図されておらず、決して実行することのないことを無理やりさせようとしてしまうのです。