Manual:Creating interface tools/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "Инструменты Qt очень легко использовать из Python, благодаря модулю Python, называемому [https://ru.wikipedia.org/...")
(Created page with "В Qt так же есть другой интересный инструмент, называемый [http://doc.qt.io/qt-4.8/designer-manual.html Qt Designer], полно...")
Line 16: Line 16:
Инструменты Qt очень легко использовать из Python, благодаря модулю Python, называемому [https://ru.wikipedia.org/wiki/PySide Pyside] (есть и другие модули Python для взаимодействия с Qt из Python). Этот модуль обеспечивает создание и взаимодействовать с виджетами, считывать что пользователи делают с ними (что вписывают в текстовые боксы) или делать что-то когда, например, нажимается кнопка.
Инструменты Qt очень легко использовать из Python, благодаря модулю Python, называемому [https://ru.wikipedia.org/wiki/PySide Pyside] (есть и другие модули Python для взаимодействия с Qt из Python). Этот модуль обеспечивает создание и взаимодействовать с виджетами, считывать что пользователи делают с ними (что вписывают в текстовые боксы) или делать что-то когда, например, нажимается кнопка.


Qt also provides another interesting tool called [http://doc.qt.io/qt-4.8/designer-manual.html Qt Designer], which is today embedded inside a bigger application called [https://en.wikipedia.org/wiki/Qt_Creator Qt Creator]. It allows to design dialog boxes and interface panels graphically, instead of having to code them manually. In this chapter, we will use Qt Creator to design a panel widget that we will use in the '''Task''' panel of FreeCAD. So you will need to download and install Qt Creator from its [https://www.qt.io/ide/ official page] if you are on Windows or Mac (on Linux it will usually be available from your software manager application).
В Qt так же есть другой интересный инструмент, называемый [http://doc.qt.io/qt-4.8/designer-manual.html Qt Designer], полностью встроенный в большое приложение [https://en.wikipedia.org/wiki/Qt_Creator Qt Creator]. Он позволяет проектировать диалоговые боксы и интерфейсные панели графически, вместо того чтобы делать это вручную. В этой главе мы будем использовать Qt Creator для проектирование панельного виджета, который использует панель '''Task''' FreeCAD. Так что Вам надо скачать и установить Qt Creator с их [https://www.qt.io/ide/ официальной страницы], если Вы на Windows или Mac (в Linux он обычно доступен из менеджера приложений).


In the following exercise, we will first create a panel with Qt Creator that asks for length, width and height values, then we will create a Python class around it, that will read the values entered by the user from the panel, and create a box with the given dimensions. This Python class will then be used by FreeCAD to display and control the task panel:
In the following exercise, we will first create a panel with Qt Creator that asks for length, width and height values, then we will create a Python class around it, that will read the values entered by the user from the panel, and create a box with the given dimensions. This Python class will then be used by FreeCAD to display and control the task panel:

Revision as of 08:26, 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 он обычно доступен из менеджера приложений).

In the following exercise, we will first create a panel with Qt Creator that asks for length, width and height values, then we will create a Python class around it, that will read the values entered by the user from the panel, and create a box with the given dimensions. This Python class will then be used by FreeCAD to display and control the task panel:

Let's start by creating the widget. Start Qt Creator, then menu File -> New File or Project -> Files and Classes -> Qt -> Qt Designer Form -> Dialog without buttons. Click Next, give it a filename to save, click Next, leave all project fields to their default value ("<none>"), and Create. FreeCAD's Task system will automatically add OK/Cancel buttons, that's why we chose here a dialog without buttons.

  • 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.
  • 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:

  • 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: