Difference between revisions of "Anchor Docking Step by step example/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 56: Line 56:
 
**** Сделайте '''Align = Client''' в инспекторе объектов
 
**** Сделайте '''Align = Client''' в инспекторе объектов
  
= Step 2: Create our tool bar =
+
= Шаг 2: Создание своей панели инструментов =
  
I'm not going to pretend that I know how to create a proper toolbar... ala excel or even open office's stuff. So I'll just create a form with speed buttons that are all left aligned, and add some icons to it. Also add the dock control to it.
+
Я не собираюсь притворяться, что знаю, как создать правильную панель инструментов ... аля excel или что-то в стиле Офиса ([[user:zoltanleo|прим.перев.]]: очевидно, имеется ввиду M$Office). Поэтому я просто создам форму со speedbutton'ами, которые выровнены по левому краю, и добавлю к ней несколько значков. Также добавьте к нему элемент управления док-станцией.
  
* Create a new form (File -> New Form)
+
* Создайте новую форму (File -> New Form)  
** Resize it to look "realistic" in size. Mine's height is 61.
+
** Измените ее размер так, чтобы она выглядела «реалистично» по размеру. Высота - 61.  
** Add some load/save buttons to it (add some icons too, if you like) and '''Align = Left''' them. I added a Load and Save speedbuttons, got some glyphs from Lazarus/images/menu. In my other project I've added a new panel, and put in a combobox there. Do what you want!
+
** Добавьте к ней несколько кнопок загрузки/сохранения (добавьте несколько значков, если хотите) и '''Align = Left''' для них. Я добавил speedbuttons Load и Save, получил несколько глифов из ''Lazarus/images/menu''. В моем другом проекте я добавил новую панель и поместил туда combobox. Делай что хочешь!  
** Add the control docker
+
** Добавьте панель управления.
*** On the OnCreate event add:  
+
*** В событие OnCreate добавьте:
 
<syntaxhighlight lang=pascal>
 
<syntaxhighlight lang=pascal>
 
     ControlDocker1:=TLazControlDocker.Create(Self);
 
     ControlDocker1:=TLazControlDocker.Create(Self);
Line 70: Line 70:
 
     ControlDocker1.Manager:=Form1.DockingManager;
 
     ControlDocker1.Manager:=Form1.DockingManager;
 
</syntaxhighlight>
 
</syntaxhighlight>
** Add the appropriate units to the uses part. ('''unit1, LDockCtrl''')
+
** Добавьте соответствующие модули в раздел uses. ('''unit1, LDockCtrl''')  
** Add the variable to the Form's '''public''' class definition: '''ControlDocker1 : TLazControlDocker;'''
+
** Добавьте переменную в раздел '''public''' определения класса формы: '''ControlDocker1: TLazControlDocker;'''
  
 
= Step 3: Our tools pages =  
 
= Step 3: Our tools pages =  

Revision as of 09:10, 7 November 2019

Template:MenuTranslate

Anchor Docking : Пошаговый пример

Warning-icon.png

Предупреждение: ЭТОТ ПРИМЕР РАБОТАЕТ НЕ НА 100%, КАК БЫЛО ЗАДУМАНО. См. раздел Отладка для получения дополнительной информации.

У нас теперь есть мануал по anchor docking ... но я знаю, что люди учатся на методом тыка, а не посредством чтения ... итак, давайте делать это.

Сначала я создам новое приложение с нуля, а затем (надеюсь) мы увидим, сможем ли мы "преобразовать" в него существующее приложение (которое работало по старому способу выравнивания "Panel").

Для первого проекта я создам приложение, которое должно выглядеть так:

 +-----------------------------+
 | Main menu                   |
 +-----------------------------+
 | Toolbar (open, save etc.)   |
 +-----+-----------------------+
 | __= |                       |
 |     |                       |
 |  T  |   Main Application    |
 |  o  |                       | 
 |  o  |                       |
 |  l  +-----------------------+
 |  s  |   Output Messages     |
 +-----+-----------------------+

С панелью инструментов (Toolbar), инструментами (Tools) (несколько страниц), «Вывода сообщений» ( Output Messages) все части становятся «пристыковываемыми» (dockable). Поскольку механизм "drag-and-drop" еще не реализован, я не собираюсь пытаться добавить функциональность для перемещения частей. (Компиляция примера показывает, как это можно сделать) ... Этот проект будет лишь демонстрировать состояние «закреплено» или «не закреплено» для каждой из этих частей. (Этот проект может быть выполнен только с панелями.)

Шаг 1: Создание главной страницы

По сути, мы просто создадим новую форму, добавим в форму главное меню, а затем добавим в форму dockmanager. Я также добавляю stringgrid, чтобы показать, как она будет выглядеть.

  • Создайте новый проект
  • В Lazarus перейдите в File -> New ... -> Выберите "Application"
  • Первая форма (unit1.pas) будет частью "Main Application".
    • Перетащите компонент TMainMenu на форму.
      • Дважды щелкните компонент TMainMenu и создайте:
        • Main - File
        • FileSub - Exit
        • Main - Windows
        • WindowsSub - Dock/Undock Active Window (Пристыковать/Отстыковать активное окно) (добавьте шоткат к F11 - чтобы он был у нас)
        • WindowsSub - Save Window Positions (Сохранить позиции окна)
    • Создайте событие «OnCreate» для формы
      • Выберите форму в конструкторе форм
      • В инспекторе объектов перейдите на вкладку "events" (события) и дважды щелкните событие «OnCreate»
    • Создайте диспетчер стыковки
      • Добавьте этот код в событие OnCreate: `DockingManager:=TLazDockingManager.Create(Self);`
      • Добавьте переменную dockmanager к классу основной формы.
        • Нажмите Ctrl+ Shift+ (это приведет вас к определению события OnCreate в классе формы.)
        • Добавьте этот код в определение класса раздела public: `DockingManager: TLazDockingManager; `
    • Добавьте модуль стыковки и XMLPropStorage в раздел uses,
      • Прокрутите редактор кода до раздела uses
      • Добавьте `, LDockCtrl, XMLPropStorage` в раздел uses
    • Теперь мы просто добавим материал, чтобы он выглядел как приложение
      • Добавьте компонент StringGrid
        • Сделайте Align = Client в инспекторе объектов

Шаг 2: Создание своей панели инструментов

Я не собираюсь притворяться, что знаю, как создать правильную панель инструментов ... аля excel или что-то в стиле Офиса (прим.перев.: очевидно, имеется ввиду M$Office). Поэтому я просто создам форму со speedbutton'ами, которые выровнены по левому краю, и добавлю к ней несколько значков. Также добавьте к нему элемент управления док-станцией.

  • Создайте новую форму (File -> New Form)
    • Измените ее размер так, чтобы она выглядела «реалистично» по размеру. Высота - 61.
    • Добавьте к ней несколько кнопок загрузки/сохранения (добавьте несколько значков, если хотите) и Align = Left для них. Я добавил speedbuttons Load и Save, получил несколько глифов из Lazarus/images/menu. В моем другом проекте я добавил новую панель и поместил туда combobox. Делай что хочешь!
    • Добавьте панель управления.
      • В событие OnCreate добавьте:
     ControlDocker1:=TLazControlDocker.Create(Self);
     ControlDocker1.Name:='ToolbarForm';
     ControlDocker1.Manager:=Form1.DockingManager;
    • Добавьте соответствующие модули в раздел uses. (unit1, LDockCtrl)
    • Добавьте переменную в раздел public определения класса формы: ControlDocker1: TLazControlDocker;

Step 3: Our tools pages

We'll just create 2 different forms which are identifiably different from each other. And add the dock control to it. Do the following twice:

  • Create a new form (File -> New Form)
    • Resize it to look "realistic" in size. (I just made it about 150 wide)
    • Identify it. (I put a label on, saying tool window 1 and 2)
    • Add the control docker
      • On the OnCreate event add:
 
     ControlDocker1:=TLazControlDocker.Create(Self);
     ControlDocker1.Name:='Toolwindow1Form';  // (or 2 for the second one)
     ControlDocker1.Manager:=Form1.DockingManager;
      • Add the appropriate units to the uses part. (unit1, LDockCtrl)
      • Add the variable to the Form's public class definition: ControlDocker1 : TLazControlDocker;

Step 4: Our Message window

Just our last form... The output form. Follow the same steps as before...

  • Create a new form (File -> New Form)
    • Resize it to look "realistic" in size. (I just made it about 100 high, and quite wide)
    • Add a memo component, and align = client
    • Add the control docker
      • On the OnCreate event add:
     ControlDocker1:=TLazControlDocker.Create(Self);
     ControlDocker1.Name:='OutputForm';  // (or 2 for the second one)
     ControlDocker1.Manager:=Form1.DockingManager;
      • Add the appropriate units to the uses part. (unit1, LDockCtrl)
      • Add the variable to the Form's public class definition: ControlDocker1 : TLazControlDocker;

Step 5: Putting it all together

Now we'll just add everything together on the mainform... and see how it comes out.

  • Add all the units to the uses section in your main unit. (unit2, unit3, unit4, unit5
  • Next, we'll want to add it to the docking manager... but the problem is that the forms are not created yet at the "OnCreate" event for the main form. So, I'll move the "assigning" of the docking to the "OnActivate" event, and just set a flag that it's been done (so it doesn't do it again)
  • So: Add an Initialized variable to form1's class: Initialized : boolean;
  • At OnCreate we'll set it to "False", and then set it to true during the OnActivate Method.
  • The current "OnActivate" method.
procedure TForm1.FormActivate(Sender: TObject);
begin
  if initialized then exit;
  Initialized := true;
  // Sets the toolbaar to the top
  DockingManager.Manager.InsertControl(Form2,alTop,Form1);
  
  // Set the tool window to the left
  DockingManager.Manager.InsertControl(Form3,alLeft,Form1);
  
  // Set the second tool window IN the first
  DockingManager.Manager.InsertControl(Form4,alClient,Form3);
  
  // Set the second Message Control to the bottom
  DockingManager.Manager.InsertControl(Form5,alBottom,Form1);
end;


Отладка

This did not work 100% as expected.

Stuff that worked as expected:

  1. The Toolbar looked correct and awesome
  2. The Tool Windows' width was as expected

Stuff that didn't work as expected:

  1. The Second tool window didn't work properly, there was a page control, but the second page wasn't assigned, and the first page had the SECOND tool window assigned
  2. The Main Menu was missing
  3. The Memo was gone... though Form5 was there (maybe not? the "title" didn't read "Form5")
  4. Form5 took over all the space that was meant for the main application. Probably adding constraints to the main window would help.