Manual:Creating interface tools/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "Начнём с создания виджета. Запустите Qt Creator, затем меню '''File -> New File or Project -> Files and Classes -> Qt -> Qt Designer Fo...")
(Created page with "* Найдём в списке на левой панели '''Label''', и перетащим её на полотно нашего виджета. Дважды кликне...")
Line 26: Line 26:
[[Image:Exercise_python_06.jpg]]
[[Image:Exercise_python_06.jpg]]


* Найдём в списке на левой панели '''Label''', и перетащим её на полотно нашего виджета. Дважды кликнем размещённую метку, и изменим её текст на '''Length'''.
* Find the '''Label''' in the list in the left panel, and drag it onto the canvas of our widget. Double-click the recent placed Label, and change its text to '''Length'''.
* Правым кликом на холсте виджета выберем '''Lay out-> Lay out in a Grid'''. Это превратит наш виджет в сетку с пока ещё только одной ячейкой, занятой нашей первой меткой. Мы теперь можем добавить следующий элемент слева, справа, сверху или снизу от нашей первой метки, и сетка автоматически расширится.
* Right-click the widget canvas, and choose '''Lay out-> Lay out in a Grid'''. This will turn our widget into a grid with currently only one cell, occupied by ourfirst label. We can now add the next items at the left, right, top or bottom of our first label, and the grid will expand automatically.
* Add two more labels below the first one, and change their text to Width and Height:
* Добавим ещё две метки под первой, и изменим их текст на Width и Height:


[[Image:Exercise_python_08.jpg]]
[[Image:Exercise_python_08.jpg]]

Revision as of 11:00, 24 May 2017

В последних двух главах мы видели как создать геометрию Part и создавать параметрический объекты. Чтобы получить полный контроль за FreeCAD, осталось одно: создание инструментов, взаимодействующими с пользователем.

В большинстве случаев не стоит подвергать пользователя испытанию, когда объект конструируется с нулевыми значениями, как мы делали с прямоугольником в предыдущей главе, и затем спрашивать пользователя заполнить значения Height и Width в панели Properties. Это работает для очень малого числа объектов, но становится утомительным когда надо создать их во множестве. Лучше иметь возможность задавать Height и Width при создании прямоугольника.

Python предоставляет базовые инструменты для ввода пользовательского текста на экране:

text = raw_input("Height of the rectangle?")
print("The entered height is ",text)

Тем не менее, для этого нужна запущенная консоль Python, и при запуске нашего кода как макроса мы не всегда уверены, что консоль Python работает на пользовательской машине.

Графический интерфейс пользователя, или ГИП, GUI, то есть все части FreeCAD, отображаемые на экране (меню, панели инструментов, окно трёхмерного вида и так далее) как раз для этого: взаимодействия с пользователем. Интерфейс FreeCAD построен на Qt, широко распространённая библиотека ГИП, предоставляющая огромный набор инструментов вроде диалоговых боксов, кнопок, панелей, меток, полей ввода, или ниспадающих меню (все они в целом называются "виджетами").

Инструменты Qt очень легко использовать из Python, благодаря модулю Python, называемому Pyside (есть и другие модули Python для взаимодействия с Qt из Python). Этот модуль обеспечивает создание и взаимодействовать с виджетами, считывать что пользователи делают с ними (что вписывают в текстовые боксы) или делать что-то когда, например, нажимается кнопка.

В Qt так же есть другой интересный инструмент, называемый Qt Designer, полностью встроенный в большое приложение Qt Creator. Он позволяет проектировать диалоговые боксы и интерфейсные панели графически, вместо того чтобы делать это вручную. В этой главе мы будем использовать Qt Creator для проектирование панельного виджета, который использует панель Task FreeCAD. Так что Вам надо скачать и установить Qt Creator с их официальной страницы, если Вы на Windows или Mac (в Linux он обычно доступен из менеджера приложений).

В следующем примере мы сначала с помощью Qt Creator создадим панель, которая будет запрашивать длину, ширину и высоту, затем создадим вокруг неё класс Python, который читает введённые значения, и создадим куб с данными размерами. Класс Python затем будет использоваться FreeCAD для показа и управления панели задач:

Начнём с создания виджета. Запустите Qt Creator, затем меню File -> New File or Project -> Files and Classes -> Qt -> Qt Designer Form -> Dialog without buttons. Кликните Next, задайте имя файла для сохранения, кликните Next, оставьте все поля проекта со значениями по умолчанию ("<none>"), затем Create. Система задач FreeCAD автоматически добавит кнопки OK/Cancel, поэтому мы выбрали здесь диалог без кнопок.

  • Найдём в списке на левой панели Label, и перетащим её на полотно нашего виджета. Дважды кликнем размещённую метку, и изменим её текст на Length.
  • Правым кликом на холсте виджета выберем Lay out-> Lay out in a Grid. Это превратит наш виджет в сетку с пока ещё только одной ячейкой, занятой нашей первой меткой. Мы теперь можем добавить следующий элемент слева, справа, сверху или снизу от нашей первой метки, и сетка автоматически расширится.
  • Добавим ещё две метки под первой, и изменим их текст на Width и Height:

  • Now place 3 Double Spin Box widgets next to our Length, Width and Height labels. For each of them, in the lower left panel, which shows all the available settings for the selected widget, locate Suffix and set their suffix to mm. FreeCAD has a more advanced widget, that can handle different units, but that is not available in Qt Creator by default (but can be compiled), so for now we will use a standard Double Spin Box, and we add the "mm" suffix to make sure the user knows in which units they work:

  • Now our widget is done, we just need to make sure of one last thing. Since FreeCAD will need to access that widget and read the Length, Width and Height values, we need to give proper names to those widgets, so we can easily retrive them from within FreeCAD. Click each of the Double Spin Boxes, and in the upper right window, double-click their Object Name, and change them to something easy to remember, for example: BoxLength, BoxWidth and BoxHeight:

  • Save the file, you can now close Qt Creator, the rest will be done in Python.
  • Open FreeCAD and create a new macro from menu Macro -> Macros -> Create
  • Paste the following code. Make sure you change the file path to match where you saved the .ui file created in QtCreator:
import FreeCAD,FreeCADGui,Part

# CHANGE THE LINE BELOW
path_to_ui = "C:\Users\yorik\Documents\dialog.ui"

class BoxTaskPanel:
   def __init__(self):
       # this will create a Qt widget from our ui file
       self.form = FreeCADGui.PySideUic.loadUi(path_to_ui)

   def accept(self):
       length = self.form.BoxLength.value()
       width = self.form.BoxWidth.value()
       height = self.form.BoxHeight.value()
       if (length == 0) or (width == 0) or (height == 0):
           print("Error! None of the values can be 0!")
           # we bail out without doing anything
           return
       box = Part.makeBox(length,width,height)
       Part.show(box)
       FreeCADGui.Control.closeDialog()
       
panel = BoxTaskPanel()
FreeCADGui.Control.showDialog(panel)

In the code above, we used a convenience function (PySideUic.loadUi) from the FreeCADGui module. That function loads a .ui file, creates a Qt Widget from it, and maps names, so we can easily access the subwidget by their names (ex: self.form.BoxLength).

The "accept" function is also a convenience offered by Qt. When there is an "OK" button in a dialog (which is the case by default when using the FreeCAD Tasks panel), any function named "accept" will automatically be executed when the "OK" button is pressed. Similarly, you can also add a "reject" function which gets executed when the "Cancel" button is pressed. In our case, we omitted that function, so pressing "Cancel" will do the default behaviour (do nothing and close the dialog).

If we implement any of the accept or reject functions, their default behaviour (do nothing and close) will not occur anymore. So we need to close the Task panel ourselves. This is done with:

FreeCADGui.Control.closeDialog() 

Once we have our BoxTaskPanel that has 1- a widget called "self.form" and 2- if needed, accept and reject functions, we can open the task panel with it, which is done with these two last lines:

panel = BoxTaskPanel()
FreeCADGui.Control.showDialog(panel)

Note that the widget created by PySideUic.loadUi is not specific to FreeCAD, it is a standard Qt widget which can be used with other Qt tools. For example, we could have shown a separate dialog box with it. Try this in the Python Console of FreeCAD (using the correct path to your .ui file of course):

from PySide import QtGui
w = FreeCADGui.PySideUic.loadUi("C:\Users\yorik\Documents\dialog.ui")
w.show()

Of course we didn't add any "OK" or "Cancel" button to our dialog, since it was made to be used from the FreeCAD Task panel, which already provides such buttons. So there is no way to close the dialog (other than pressing its Window Close button). But the function show() creates a non-modal dialog, which means it doesn't block the rest of the interface. So, while our dialog is still open, we can read the values of the fields:

w.BoxHeight.value() 

This is very useful for testing.

Finally, don't forget there is much more documentation about using Qt widgets on the FreeCAD Wiki, in the Python Scripting section, which contains a dialog creation tutorial, a special 3-part PySide tutorial that covers the subject extensively.

Read more

Other languages: