Manual:Creating interface tools/fr: Difference between revisions

From FreeCAD Documentation
(Created page with "Dans l'exercice suivant, nous allons d'abord créer un panneau avec Qt Creator qui demande les valeurs de longueur, de largeur et de hauteur, alors nous allons créer une clas...")
(Created page with "Commençons par créer le widget. Démarrez Qt Creator, puis menu '''Fichier -> Nouveau fichier ou projet ->Fichiers et classes -> Qt -> Formulaire Qt Designer -> Boîte de di...")
Line 22: Line 22:
[[Image:Exercise_python_07.jpg]]
[[Image:Exercise_python_07.jpg]]


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.
Commençons par créer le widget. Démarrez Qt Creator, puis menu '''Fichier -> Nouveau fichier ou projet ->Fichiers et classes -> Qt -> Formulaire Qt Designer -> Boîte de dialogue sans boutons'''. Cliquez sur '''Suivant''', donnez lui un nom de fichier pour l’enregistrer, cliquez sur '''Suivant''', laissez tous les champs de projet à leur valeur par défaut ("<none>") et '''Créer'''. Le système de tâches de FreeCAD ajoutera automatiquement les boutons OK / Annuler, c'est pourquoi nous avons choisi ici une boîte de dialogue sans boutons.


[[Image:Exercise_python_06.jpg]]
[[Image:Exercise_python_06.jpg]]

Revision as of 21:26, 5 June 2017

Dans les deux derniers chapitres, nous avons vu comment créer la géométrie Part (create Part geometry) et créer des objets paramétriques (create parametric objects). Une dernière pièce manque pour avoir un contrôle total sur FreeCAD : Créer des outils qui interagiront avec l'utilisateur.

Dans de nombreuses situations, il n'est pas très convivial de construire un objet avec des valeurs nulles, comme nous avons fait avec le rectangle dans le chapitre précédent, puis de demander à l'utilisateur de remplir la hauteur et la largeur dans le panneau Propriétés. Cela fonctionne pour un très petit nombre d'objets, mais devient très fastidieux si vous avez beaucoup de rectangles à réaliser. Une meilleure façon serait d'être capable de donner déjà la hauteur et la largeur lors de la création du rectangle.

Python offre un outil de base permettant à l'utilisateur de saisir du texte à l'écran :

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

Cependant, cela nécessite une console Python en cours d'exécution et, lors de l'exécution de notre code à partir d'une macro, nous ne sommes pas toujours sûrs que la console Python sera activée sur la machine de l'utilisateur.

L'interface utilisateur graphique (Graphical User Interface), ou GUI, c'est-à-dire toute la partie de FreeCAD qui s'affiche sur votre écran (le menu, les barres d'outils, la vue 3D, etc.) est tout à cette fin : interagir avec l’utilisateur. L'interface de FreeCAD est construite avec Qt, une trousse d'outils GUI open source très commune qui qffre une large gamme d'outils tels que les boîtes de dialogue, les boutons, les étiquettes, les boîtes de saisie de texte ou les menus déroulants (tout cela est généralement appelé "widgets").

Les outils Qt sont très faciles à utiliser depuis Python, grâce à un module Python appelé Pyside (Il existe aussi plusieurs autres modules Python pour communiquer avec Qt depuis Python). Ce module vous permet de créer et d'interagir avec des widgets, lire ce que l'utilisateur a fait avec eux (ce qui a été rempli dans des zones de texte) ou faire des choses quand, par exemple, un bouton a été pressé.

Qt fournit également un autre outil intéressant appelé Qt Designer, aujourd'hui incorporé à l'intérieur d’une plus grande application appelée Qt Creator. Il permet de concevoir des boîtes de dialogue et des panneaux d'interface graphiquement, au lieu d'avoir à les coder manuellement. Dans ce chapitre, nous utiliserons Qt Creator pour dessiner un widget de panneau que nous utiliserons dans le panneau des tâches de FreeCAD. Donc, vous devrez télécharger et installer Qt Creator à partir de sa page officielle (official page) si vous êtes sur Windows ou Mac (sur Linux, il sera généralement disponible auprès de votre application de gestionnaire de logiciels).

Dans l'exercice suivant, nous allons d'abord créer un panneau avec Qt Creator qui demande les valeurs de longueur, de largeur et de hauteur, alors nous allons créer une classe Python autour de lui, qui lira les valeurs entrées par l'utilisateur à partir du panneau, et créer une boîte avec les dimensions données. Cette classe Python sera ensuite utilisée par FreeCAD pour afficher et contrôler le panneau des tâches :

Commençons par créer le widget. Démarrez Qt Creator, puis menu Fichier -> Nouveau fichier ou projet ->Fichiers et classes -> Qt -> Formulaire Qt Designer -> Boîte de dialogue sans boutons. Cliquez sur Suivant, donnez lui un nom de fichier pour l’enregistrer, cliquez sur Suivant, laissez tous les champs de projet à leur valeur par défaut ("<none>") et Créer. Le système de tâches de FreeCAD ajoutera automatiquement les boutons OK / Annuler, c'est pourquoi nous avons choisi ici une boîte de dialogue sans boutons.

  • 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