Outils pour utilisateurs

Outils du site


issue73:python

Table des matières

1

We are going to take a short detour this month from our TVRage program to partially answer a question from a reader. I was asked to talk about QT Creator, and how to use it to design user interfaces for Python programs. Unfortunately, from what I can tell, the support for QT Creator isn't ready yet for Python. It IS being worked on, but is not “ready for prime time” quite yet. So, in an effort to get us ready for that future article, we will work with QT4 Designer. You will need to install (if they aren't already) python-qt4, qt4-dev-tools, python-qt4-dev, pyqt4-dev-tools and libqt4-dev. Once that is done, you can find QT4 Designer under Applications | Programming. Go ahead and start it up. You should be presented with something like the following: Make sure that 'Main Window' is selected, and click the 'Create' button. Now you will have a blank form that you can drag and drop controls onto.

Nous allons laisser de côté ce mois-ci notre programme TVRage pour répondre en partie à une question d'un lecteur. On m'a demandé de parler de Qt Creator et comment l'utiliser pour concevoir des interfaces utilisateur pour des programmes Python.

Malheureusement, que je sache, le support de Qt Creator n'est pas encore prêt pour Python. Il est effectivement en cours d'élaboration, mais n'est pas tout à fait « prêt pour les heures de grande écoute ».

Ainsi, afin de nous préparer pour ce futur article, nous allons travailler avec QT4 Designer. Vous aurez besoin d'installer (si ce n'est pas déjà fait) python-qt4, qt4-dev-tools, python-qt4-dev, pyqt4-dev-tools et libqt4-dev.

Une fois que c'est fait, vous trouverez QT4 Designer sous Applications | Programmation. Allez-y et lancez-le. Vous devriez voir quelque chose comme ceci :

Assurez-vous que « Main Window » est sélectionné et cliquez sur le bouton « Créer ». Vous verrez alors un formulaire vierge sur lequel vous pouvez faire glisser et déplacer des contrôles.

2

The first thing we want to do is resize the main window. Make it about 500×300. You can tell how big it is by looking at the Property Editor under the geometry property on the right side of the designer window. Now, scroll down on the property editor list box until you see 'windowTitle'. Change the text from 'MainWindow' to 'Python Test1'. You should see the title bar of our design window change to 'Python Test1 – untitled*'. Now is a good time to save our project. Name it 'pytest1.ui'. Next, we will put a button on our form. This will be an exit button to end the test program. On the left side of the designer window you will see all of the controls that are available. Find the 'Buttons' section and drag and drop the 'Push Button' control onto the form. Unlike the GUI designers we have used in the past, you don't have to create grids to contain your controls when you use QT4 Designer. Move the button to near center-bottom of the form. If you look at the Property Editor under geometry, you will see something like this: [(200,260), 97×27] In the parentheses are the X and Y positions of the object (push-button in this case) on the form, followed by its width and height. I moved mine to 200,260.

La première chose à faire est de redimensionner la fenêtre principale. Réglez-la à environ 500×300. Vous pouvez voir sa taille en regardant l'éditeur de propriétés dans la partie « géométrie » sur le côté droit de la fenêtre du concepteur. Maintenant, faites défiler vers le bas la liste de l'éditeur de propriétés jusqu'à ce que vous voyiez « windowTitle ». Remplacez le texte « MainWindow » par « Python Test1 ». Vous devriez voir le changement dans la barre de titre de la fenêtre de conception : « Python Test1 - untitled* ». C'est maintenant un bon moment pour sauvegarder notre projet. Nommez-le “pytest1.ui». Ensuite, nous allons mettre un bouton sur notre formulaire. Ce sera un bouton pour quitter le programme de test. Sur le côté gauche de la fenêtre du concepteur, vous verrez toutes les commandes qui sont disponibles. Trouvez la section « Buttons » et faites glisser un « Push Button » sur le formulaire. Contrairement aux concepteurs graphiques que nous avons utilisés dans le passé, vous n'avez pas à créer des grilles pour contenir vos contrôles lorsque vous utilisez QT4 Designer. Déplacez le bouton presque au centre en bas du formulaire. Si vous regardez l'éditeur de propriétés sous « géométrie », vous verrez quelque chose comme ceci :

[(200,260), 97×27]

Dans les parenthèses se trouvent les positions X et Y de l'objet (bouton-poussoir dans ce cas) sur le formulaire, suivies par sa largeur et sa hauteur. J'ai positionné le mien en 200,260.

3

Just above that is the objectName property—which, by default, is set to 'pushButton'. Change that to 'btnExit'. Now scroll down on the Property Editor list to the 'QAbstractButton' section, and set the 'text' property to 'Exit'. You can see on our form that the text on the button has changed. Now, add another button and position it at 200,200. Change its objectName property to 'btnClickMe,' and set the text to 'Click Me!'. Next add a label. You will find it in the toolbox on the left under 'DisplayWidgets'. Put it close to the center of the form (I put mine at 210,130), and set its objectName property to lblDisplay. We will want to make it bigger than what it is by default, so set its size to somewhere around 221 x 20. In the property editor, scroll down to the 'Qlabel’ section, and set the Horizontal alignment to 'AlignHCenter'. Change the text to blank. We will set the text in code—when the btnClickMe is clicked. Now save the project again.

Juste au-dessus se trouve la propriété « objectName » qui, par défaut, est réglée sur « pushButton ». Changez cela en « btnQuitter». Maintenant, faites défiler vers le bas la liste de l'éditeur de propriétés jusqu'à la section « QAbstractButton », et définissez la propriété « text » à « Quitter ». Vous pouvez voir sur notre formulaire que le texte sur le bouton a changé.

Maintenant, ajoutez un autre bouton et positionnez-le en 200,200. Réglez sa propriété objectName à « btnCliqueMoi » et son texte à « Cliquez-moi ! ».

Ensuite, ajoutez une étiquette (Label). Vous la trouverez dans la boîte à outils sur la gauche, sous « DisplayWidgets ». Mettez-la à proximité du centre du formulaire (j'ai mis la mienne en 210,130), et réglez sa propriété objectName à lblAffichage. Nous voulons la rendre plus grande qu'elle n'est par défaut, réglez donc sa taille à quelque chose comme 221 x 20. Dans l'éditeur de propriétés, descendez jusqu'à la section « QLabel », et définissez l'alignement horizontal à « AlignHCenter » (AlignementCentreH). Modifiez le texte en blanc. Nous réglerons le texte dans le code lorsque le btnCliqueMoi sera cliqué. Maintenant, sauvegardez à nouveau le projet.

4

Slots & Signals This next section might be a bit difficult to wrap your head around, especially if you have been with us for a long time and have dealt with the previous GUI designers. In the other designers, we used events that were raised when an object was clicked, like a button. In QT4 Designer, events are called Signals, and the function that is called by that signal is called a Slot. So, for our Exit button, we use the Click signal to call the Main Window Close slot. Are you totally confused right now? I was when I first dealt with QT, but it begins to make sense after a while. Fortunately, there is a very easy way to use predefined slots & signals. If you press the F4 button on the keyboard, you will be in the Edit Signals & Slots mode. (To get out of the Edit Signals & Slots mode, press F3.) Now, left click and hold on the Exit button, and drag slightly up and to the right, off the button onto the main form, then release the click. You will see a dialog pop up that looks something like that shown above.

Slots et signaux

La section suivante est peut-être un peu difficile à faire entrer dans votre tête, surtout si vous avez été avec nous pendant une longue période et avez utilisé les concepteurs graphiques précédents. Dans les autres concepteurs, nous avons utilisé des événements qui se sont déclenchés quand on a cliqué sur un objet, comme un bouton. Avec QT4 Designer, les événements s'appellent des signaux et la fonction appelée par ce signal s'appelle un slot. Donc, pour notre bouton Quitter, nous utilisons le signal « cliquer » pour appeler le slot « fermeture de la fenêtre principale ». Êtes-vous totalement perdus maintenant ? Je l'étais quand j'ai eu affaire à QT au début, mais cela commence à sembler logique après un certain temps.

Heureusement, il existe un moyen très simple pour utiliser les slots et les signaux prédéfinis. Si vous appuyez sur la touche F4 du clavier, vous irez dans le mode d'édition des signaux et des slots. (Pour sortir du mode d'édition, appuyez sur F3.) Maintenant, faites un clic gauche et maintenez le bouton Quitter enfoncé, puis faites glisser légèrement vers le haut et vers la droite, en dehors du bouton et sur le formulaire principal, puis relâchez le clic. Vous verrez une fenêtre de dialogue qui ressemble à celle ci-dessus.

5

This will give us an easy way to connect the clicked signal to the form. Select the first option on the left which should be 'clicked()'. This will enable the right side of the window and select the 'close()' option from the list, then click 'OK'. You will see something that looks like this: The click signal (event) is linked to the Close routine of the main window. For the btnClickMe clicked signal, we will do that in code. Save the file one more time. Exit QT4 Designer and open a terminal. Change to the directory that you saved the file in. Now we will generate a python file by using the command line tool pyuic4. This will read the .ui file. The command will be: pyuic4 -x pytest1.ui -o pytest1.py

Cela nous donnera un moyen facile de connecter le signal « clicked » au formulaire. Sélectionnez la première option sur la gauche qui devrait être « clicked() ». Cela activera la partie droite de la fenêtre et sélectionnera l'option « close() » dans la liste, puis cliquez sur « OK ». Vous verrez quelque chose qui ressemble à ceci :

Le signal de clic (événement) est lié à la routine de clôture de la fenêtre principale.

Pour le signal clicked de btnCliqueMoi, nous le gérerons dans le code.

Enregistrez le fichier une fois de plus. Quittez QT4 Designer et ouvrez un terminal. Allez dans le répertoire où vous avez enregistré le fichier. Maintenant, nous allons générer un fichier python en utilisant l'outil en ligne de commande pyuic4. Cela va lire le fichier .ui. La commande sera :

pyuic4 -x pytest1.ui -o pytest1.py

6

The -x parameter says to include the code to run and display the UI. The -o parameter says to create an output file rather than just display the file in stdout. One important thing to note here. Be SURE to have everything done in QT4 Designer before you create the python file. Otherwise, it will be completely rewritten and you'll have to start over from scratch. Once you've done this, you will have your python file. Open it up in your favorite editor. The file itself is only about 65 lines long, including comments. We had only a few controls so, it wouldn't be very long. I'm not going to show a great deal of the code. You should be able to follow most all of the code by now. However we will be creating and adding to the code in order to put the functionality in to set the label text. The first thing we need to do is copy the signal & slot line and modify it. Somewhere around line 47 should be the following code: QtCore.QObject.connect(self.btnExit, QtCore.SIGNAL(_fromUtf8(“clicked()”)), MainWindow.close)

Le paramètre -x indique d'inclure le code pour exécuter et afficher l'interface utilisateur. Le paramètre -o indique de créer un fichier de sortie plutôt que de simplement afficher le fichier sur la sortie standard. Une chose importante à noter ici : assurez-vous d'avoir vraiment tout fait dans QT4 Designer avant de créer le fichier python, sinon il sera complètement réécrit et vous devrez recommencer à partir de zéro.

Une fois que vous aurez fait cela, vous aurez votre fichier python. Ouvrez-le dans votre éditeur de texte favori.

Le fichier lui-même ne contient que 65 lignes environ, y compris les commentaires. Nous n'avons placé que quelques contrôles, c'est pour cela qu'il n'est pas très long. Je ne vais pas montrer beaucoup de code. Vous devriez être en mesure de suivre la plupart du code maintenant. Cependant, nous allons créer et ajouter d'autres codes afin de mettre la fonctionnalité pour définir le texte de l'étiquette.

La première chose que nous devons faire est de copier la ligne de signal et de slot et la modifier. Quelque part autour de la ligne 47 devrait se trouver le code suivant :

QtCore.QObject.connect(self.btnQuitter, QtCore.SIGNAL(_fromUtf8(“clicked()”)), MainWindow.close)

7

Copy that, and, right below it, paste the copy. Then change it to: QtCore.QObject.connect(self.btnClickMe, QtCore.SIGNAL(_fromUtf8(“clicked()”)), self.SetLabelText) This will then create the signal/slot connection to our routine that will set the label text. Under the retranslateUi routine add the following code: def SetLabelText(self): self.lblDisplay.setText(_fromUtf8(“That Tickles!!!”)) I got the label setText information from the initialization line in the setupUi routine. Now run your code. Everything should work as expected.

Copiez-le, et recollez-le juste en dessous. Puis modifiez-le en :

QtCore.QObject.connect(self.btnCliqueMoi, QtCore.SIGNAL(_fromUtf8(“clicked()”)), self.reglerAffichage)

Ceci va créer la connexion signal/slot pour notre routine qui va régler le texte de l'étiquette. Sous la routine retranslateUi, ajoutez le code suivant :

def reglerAffichage (self):          self.lblDisplay.setText (_fromUtf8 (“Ca chatouille !”))

J'ai trouvé le nom setText dans la ligne d'initialisation dans la routine setupUi.

Maintenant, exécutez votre code. Tout devrait fonctionner comme prévu.

8

Although this is a VERY simple example, I'm sure you are advanced enough to play with QT4 Designer and get an idea of the power of the tool. Next month, we will return from our detour and start working on the user interface for our TVRage program. As always, the code can be found on pastebin at http://pastebin.com/98fSasdb for the .ui code, and http://pastebin.com/yC30B885 for the python code. See you next time.

Bien que ce soit un exemple très simple, je suis sûr que vous êtes assez avancé pour jouer avec QT4 Designer et vous faire une idée de la puissance de l'outil.

Le mois prochain, nous reviendrons de notre détour et commencerons à travailler sur l'interface utilisateur pour notre programme de TVRage.

Comme toujours, le code peut être trouvé sur pastebin à http://pastebin.com/FniB3s85 pour le code .ui et http://pastebin.com/K7zViFu3 pour le code python. [NdT: code traduit par l'équipe francophone. Pour le code original, voir http://pastebin.com/98fSasdb pour le code .ui et http://pastebin.com/yC30B885 pour le code python]

Rendez-vous la prochaine fois.

issue73/python.txt · Dernière modification : 2013/09/18 14:49 de andre_domenech