Outils pour utilisateurs

Outils du site


issue73:python

Ceci est une ancienne révision du document !


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, d'après ce que je peux dire, le support de Qt Creator n'est pas encore prêt pour Python. Il est en cours d'élaboration, mais n'est pas tout à fait « prêt pour la grande sortie ».

Ainsi, dans un effort pour nous préparer pour ce prochain 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 pouvez trouver QT4 Designer sous Applications | Programmation. Allez-y et lancez-le. Vous devriez voir quelque chose comme ceci :

Assurez-vous que la fenêtre principale est sélectionnée 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 voyez « 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 le bon moment pour sauver 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 « Boutons » et faites glisser un « Push Buton » sur le formulaire. Contrairement aux concepteurs graphiques que nous avons utilisé 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 à proximité du 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.

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.

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

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)

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.

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.

issue73/python.1378040838.txt.gz · Dernière modification : 2013/09/01 15:07 de fredphil91