Graphical User Interfaces

2y ago
33 Views
2 Downloads
3.64 MB
24 Pages
Last View : 2m ago
Last Download : 2m ago
Upload by : Laura Ramon
Transcription

Chapter 14Graphical User InterfacesSo far, we have developed programs that interact with the user through the command line, where the user has to call aPython program by typing its name and adding the sequence of arguments.Having a visual environment for the program variables and results extremely simplify the interaction between theuser and the application. This kind of environments are known as a Graphical User Interfaces (GUI). Graphicalinterfaces are present in various types of devices and platforms, such as web form or a smartphone application. Most,if not all, graphical user interface based applications use an event management based architecture. Applicationsoperated by command line perform data input and output at specific times and circumstances established within theprogram. However, every time we interact with an application graphically, the program does not know beforehandwhen actions will occur. The user may enter data, press a key, move the mouse, or click on any widget within theinterface. Therefore, the code must be written to respond to all these events. It is always possible to design a graphicalinterface from the beginning to the end by interacting directly with each pixel. Never the less, there are now optimizedmodules that provide generic graphical elements such as buttons, bars, text boxes, and calendars. These modulesgreatly facilitate the development of graphical interfaces. In this course, we will focus on the use of PyQt.14.1 PyQtPyQt is a Python library that includes several modules that help with the development of graphical interfaces, here wedescribe some of the modules included in PyQt: QtCore: includes non-GUI functionalities like file and directory management, time, and URLs, among others. QtGui: includes visual components such as buttons, windows, drop-down lists, etc.

292CHAPTER 14. GRAPHICAL USER INTERFACES QtNetwork: provides classes to program graphical applications based on TCP/IP, UDP, and some other networkprotocols. QtXml: includes XML file handling functionalities. QtSvg: provides classes to display vector graphics files (SVG). QtOpenGL: contains functions for 3D and 2D graphics rendering using OpenGL. QtSql: includes functionalities for working with SQL databases.To create a window we use the QtGui module. The first step is to build the application that will contain the windowand all its elements or Widgets. This procedure is done through the QApplication class, which includes event loop,application initialization and closing, input arguments handling, among other responsibilities. For every applicationthat PyQt uses, there is only one QApplication object regardless of the number of windows that this applicationhas.1# codes 1.py23from PyQt4 import QtGui456class MiForm(QtGui.QWidget):7# The next line defines the window geometry.8# Parameters: (x top left, y top left, width, height)9self.setGeometry(200, 100, 300, 300)10self.setWindowTitle('My First Window')# Optional111213if name ' main ':14app QtGui.QApplication([])15form MiForm()16form.show()17app.exec ()The QtGui.QWidget class from which the MyForm class descends, is the base class for all objects in PyQt. Theconstructor for this class has no default parents, in which case corresponds to an empty window. We also have todefine the window properties, so far only defined in memory. To display the window on the screen, we must use the

14.1. PYQT293show() method. Finally, the exec () method executes the main loop to perform the event detection. The result ofthe above code corresponds to the clear interface as shown in Figure 14.1.Figure 14.1: Example of an empty window generated by PyQt.In PyQt there are useful objects or Widgets to control information input and output in graphical interfaces. These arelabels and text boxes. Labels are used to display form variables or static strings. In PyQt these are represented by theQLabel class. Text boxes also allow text handling in the interface, primarily as a means of entering data into theform. In PyQt interface they are created by QLineEdit class:1# codes 2.py23from PyQt4 import QtGui4567class MiForm(QtGui.QWidget):def init (self):8super(). init ()9self.init GUI()1011def init GUI(self):12# Once the form is called, this method initializes the13# interface and all of its elements and Widgets1415self.label1 QtGui.QLabel('Text:', self)16self.label1.move(10, 15)17

294CHAPTER 14. GRAPHICAL USER INTERFACES18self.label2 QtGui.QLabel('This label is modifiable', self)19self.label2.move(10, 50)2021self.edit1 QtGui.QLineEdit('', self)22self.edit1.setGeometry(45, 15, 100, 20)2324# Adds all elements to the form25self.setGeometry(200, 100, 200, 300)26self.setWindowTitle('Window with buttons')27282930if name ' main ':app QtGui.QApplication([])3132# A window that inherits from QMainWindow is created33form MiForm()34form.show()35app.exec ()The code above clarifies how to use Labels and LineEdits within the GUI. Figure 14.2 shows the results.Figure 14.2: Example of a QLabel within a Widget.PyQt also includes several useful graphical objects to control the interface.The most basic is thePushButton(label, father, function) element, which embeds a button in the window. The result

14.1. PYQT295generated by the code below is a window with a button as shown in the Figure 14.3.1# codes 3.py23from PyQt4 import QtGui4567class MyForm(QtGui.QWidget):def init (self):8super(). init ()9self.init GUI()1011def init GUI(self):12# Once the form is called, this method initializes the13# interface and all of its elements and Widgets14self.label1 QtGui.QLabel('Text:', self)15self.label1.move(10, 15)1617self.label2 QtGui.QLabel('Write the answer here', self)18self.label2.move(10, 50)1920self.edit1 QtGui.QLineEdit('', self)21self.edit1.setGeometry(45, 15, 100, 20)2223# The use of the & symbol at the start of the text within24# any button or menu makes it so the first letter is shown25# in bold font. This visualization may depend on the used26# platform.27self.button1 QtGui.QPushButton('&Process', )29self.button1.move(5, 70)3031# Adds all elements to the form32self.setGeometry(200, 100, 200, 300)33self.setWindowTitle('Window with buttons')34self.show()

296CHAPTER 14. GRAPHICAL USER INTERFACES35363738if name ' main ':app QtGui.QApplication([])3940# A window that inherits from QMainWindow is created41form MyForm()42form.show()43app.exec ()Figure 14.3: A simple window with a button.Main WindowWindows created by QWidget correspond to windows that may contain other Widgets. PyQt offers a more completetype of window called MainWindow. It creates the standard skeleton of an application including a status bar, toolbar,and menu bar, as shown in the Figure 14.4.The status bar allows us to display application status information. To create this, the statusBar() method (belongsto QApplication class) is used. Messages in the status bar are updated when the user interacts with the rest ofthe application. The menu bar is a typical part of a GUI-based application. It corresponds to a group of structuredand logically grouped commands inside of menus. The toolbar provides quick access to the most frequently usedcommands. Finally, the Central Widget or core content area corresponds to the body of the window. It may containany Widget in QtGui, as well as one of the forms created in the previous examples. To add this Widget or form to

14.1. PYQT297Figure 14.4: Diagram of the classic MainWindow layout.the central Widget, the setCentralWidget(Widget) method must be used. The next example shows how tointegrate the elements described in the main window:1# codes 4.py23from PyQt4 import QtGui45678class MainForm(QtGui.QMainWindow):def init (self):super(). init ()910# Configures window geometry11self.setWindowTitle('Window with buttons')12self.setGeometry(200, 100, 300, 250)1314# Action definitions15see status QtGui.QAction(QtGui.QIcon(None), '&Change ''Status', self)1617see status.setStatusTip('This is a test item')

29818CHAPTER 14. GRAPHICAL USER INTERFACESsee status.triggered.connect(self.change status bar)1920exit QtGui.QAction(QtGui.QIcon(None), '&Exit', self)21# We can define a key combination to execute each command22exit.setShortcut('Ctrl Q')23# This method shows the command description on the status bar24exit.setStatusTip('End the app')25# Connects the signal to the slot that will handle this # Menu and menu bar creation29menubar self.menuBar()30file menu menubar.addMenu('&File')31file menu.addAction(see status)32file menu.addAction(exit)# first menu3334other menu menubar.addMenu('&Other Menu')# second menu3536# Includes the status bar37self.statusBar().showMessage('Ready')3839# Sets the previously created form as the central widged40self.form f change status bar(self):self.statusBar().showMessage('Status has been changed')45464748class MyForm(QtGui.QWidget):def init (self):49super(). init ()50self.init GUI()5152def init GUI(self):

14.1. PYQT29953self.label1 QtGui.QLabel('Text:', self)54self.label1.move(10, 15)5556self.label2 QtGui.QLabel('Write the answer here', self)57self.label2.move(10, 50)5859self.edit1 QtGui.QLineEdit('', self)60self.edit1.setGeometry(45, 15, 100, 20)6162self.button1 QtGui.QPushButton('&Process', )64self.button1.move(5, 70)6566self.setGeometry(200, 100, 200, 300)67self.setWindowTitle('Window with buttons')68self.show()6970def button pressed(self):71sender self.sender()72self.label3.setText('Signal origin: lf.label3.sizeHint())7475def button1 .sizeHint())78798081if name ' main ':app QtGui.QApplication([])8283form MainForm()84form.show()85app.exec ()

30014.2CHAPTER 14. GRAPHICAL USER INTERFACESLayoutsLayouts allow a more flexible and responsive way to manage and implement Widget distribution in the interfacewindow. Each Widget’s move(x, y) method allows absolute positioning of all objects in the window. However, ithas limitations, such as; Widget position does not change if we resize the window, and Application’s look will vary ondifferent platforms or display settings.To avoid redoing the window for better distribution, we use box layouts. Two basic types allow Widget horizontaland vertical alignment: QtGui.QHBoxLayout() and QtGui.QVBoxLayout(). In both cases, Widgets aredistributed within the layout occupying all available space, even if we resize the window. Objects must be added to eachlayout by the addWidget method. Finally, the box layout must be loaded to the window as self.setLayout().We can add the vertical alignment of objects by including the horizontal layout within a vertical layout. The followingcode shows an example of how to create a layout such that three Widgets are aligned in the bottom right corner. Figure14.5 shows the output:1# codes 5.py23from PyQt4 import QtGui45678class MainForm(QtGui.QMainWindow):def init (self):super(). init ()910# Window geometry11self.setWindowTitle('Window with buttons')12self.setGeometry(200, 100, 300, 250)1314self.form class MiForm(QtGui.QWidget):def init (self):20super(). init ()21self.init GUI()

14.2. LAYOUTS3012223def init GUI(self):24self.label1 QtGui.QLabel('Text:', self)25self.label1.move(10, 15)2627self.edit1 QtGui.QLineEdit('', self)28self.edit1.setGeometry(45, 15, 100, 20)2930self.button1 QtGui.QPushButton('&Calculate', )3233# QHBoxLayout() and QVBoxLayout() are created and added to the34# Widget list by using the addWidget() method. The stretch()35# method includes a spacing that expands the layout towards36#37hbox ox.addWidget(self.button1)the right and downwards.4243vbox ayout(hbox)4647# The vertical layout contains the horizontal layout48self.setLayout(vbox)49505152if name ' main ':app QtGui.QApplication([])5354form MainForm()55form.show()56app.exec ()

302CHAPTER 14. GRAPHICAL USER INTERFACES(a)(b)Figure 14.5: This figure shows the possible results after executing the code above. (a) Shows only usingQHBoxLayout. (b) Shows using QHBoxLayout and QVBoxLayout.PyQt includes a class to distribute widgets in a matrix-like grid within the window, called QGridLayout(). Thistype of layout divides the window space into rows and columns. Each Widget must be added to a cell in the grid byusing the addWidget(Widget, i, j) method. For example, the following code shows an example to create amatrix similar to a mobile phone keypad buttons. The output can be seen in Figure 14.6.1# codes 6.py234class MyForm(QtGui.QWidget):def init (self):5super(). init ()6self.init GUI()789def init GUI(self):# Creating the grid that will position Widgets in a matrix10# like manner11grid s ['1', '2', '3',15'4', '5', '6',16'7', '8', '9',

14.3. EVENTS AND SIGNALS17303'*', '0', '#']1819positions [(i, j) for i in range(4) for j in range(3)]20212223for positions, value in zip(positions, values):if value '':continue2425# The * symbol allows unpacking positions as26# independent arguments27button QtGui.QPushButton(value)28grid.addWidget(button, * positions)2930self.move(300, ()Figure 14.6: Example of numeric keypad using QGridLayout to organize the buttons in a grid.14.3 Events and SignalsGraphical interfaces are applications focused mainly on handling events. This strategy allows detecting user actions onthe interface asynchronously. The same application can generate events A. In PyQt these events are detected oncethe application enters the main loop started by the exec () method. Figure 14.6 shows a flowchart comparison

304CHAPTER 14. GRAPHICAL USER INTERFACESbetween a program with a linear structure and a program using GUI-based event handling. In this model there arethree fundamental elements: The source of the event: corresponds to the object that generates the change of state or that generates the event The event object: the object that encapsulates the change of status through the event. The target object: the object to be notified of the status changeUnder this model, the event source delegates the task of managing the event to the target object. PyQt, on its 4thversion, uses the signal and slot mechanism to handle events. Both elements are used for communication betweenobjects. When an event occurs, the activated object generates signals, and any of those signals calls a slot. Slots can beany callable Python object.Below, we see a modification to the previous program so that it generates a call to the boton1 callback()function, after button1 is pressed. This is accomplished using the event to send the signal. In the case of buttons,the signal corresponds to the clicked method. By using the connect() method, communication between objectsinvolved in the event is set. This method receives a Python callable function, i.e., boton1 callback without ().1# codes 7.py234class MyForm(QtGui.QWidget):def init (self):5super(). init ()6self.init GUI()78910def init GUI(self):self.label1 QtGui.QLabel('Text:', self)self.label1.move(10, 15)1112self.label2 QtGui.QLabel('Write your answer here', self)13self.label2.move(10, 50)1415self.edit1 QtGui.QLineEdit('', self)16self.edit1.setGeometry(45, 15, 100, 20)1718# Connecting button1 signal to other object

14.4. SENDER30519self.button1 QtGui.QPushButton('&Process', )21self.button1.move(5, 70)22# This object MUST be callable. self.button1 callback()23# would not work.24self.button1.clicked.connect(self.button1 callback)2526self.button2 QtGui.QPushButton('&Exit', self.button2.sizeHint())30self.button2.move(90, 70)3132self.setGeometry(200, 100, 200, 300)33self.setWindowTitle('Window with buttons')3435def button1 callback(self):36# This method handles the event37self.label2.setText(self.edit1.text())14.4 SenderSometimes we need to know which of the objects on the form sent a signal. PyQt offers the sender() method. Wecan see an example by adding a new label to the form that will display the name of the widget that sends the signal:1# codes 8.py23def init GUI(self):4self.label1 QtGui.QLabel('Text:', self)5self.label1.move(10, 15)67self.label2 QtGui.QLabel('Write your answer here:', self)8self.label2.move(10, 50)910self.label3 QtGui.QLabel('Signal origin:', self)11self.label3.move(10, 250)

306CHAPTER 14. GRAPHICAL USER INTERFACES1213self.edit1 QtGui.QLineEdit('', self)14self.edit1.setGeometry(45, 15, 100, 20)1516self.button1 QtGui.QPushButton('&Process', )18self.button1.move(5, 70)19self.button1.clicked.connect(self.button1 n pressed)2122self.button2 QtGui.QPushButton('&Exit', lf.button2.sizeHint())25self.button2.move(90, 70)2627self.setGeometry(200, 100, 300, 300)28self.setWindowTitle('Window with buttons.')29self.show()303132def button pressed(self):33# This method registers the object sending the signal and shows it in34# label3 by using the sender() method35sender self.sender()36self.label3.setText('Signal origin: lf.label3.sizeHint())383940def button1 1.text())Creating Custom SignalsIn PyQt it is also possible to define user-customized signals. In this case, we must create the object that will host thenew signal. These signals are a subclass of QtCore.QObject. Within the object the new signal is created as an

14.5. CREATING CUSTOM SIGNALS307instance of the object QtCore.pyqtSignal(). Then, the signal and its handling functions if required, must becreated in the form. The example below shows a simple way to generate a new signal that activates when one of thebuttons is pressed. To emit the signal the emit() method inherited from pyqtSignal() is used:1# codes 9.py23import sys4from PyQt4 import QtGui, QtCore567class MySignal(QtCore.QObject):8# This class defines the new signal 'signal writer'9signal writer QtCore.pyqtSignal()10111213class MyForm(QtGui.QWidget):def init (self):14super(). init ()15self.initialize GUI()1617def initialize GUI(self):18self.s MySignal()19self.s.signal writer.connect(self.write label)2021self.label1 QtGui.QLabel('Label', self)22self.label1.move(20, etGeometry(300, 300, 290, 150)26self.setWindowTitle('Signal Emitter')27self.show()2829def mousePressEvent(self, event):30# This method handles when any of the mouse buttons is pressed. It is31# defined by default within the app. It can be overwritten according32# to how the event should be handled in each app.

308CHAPTER 14. GRAPHICAL USER INTERFACESself.s.signal writer.emit()3334def write label(self):3536self.label1.setText('Mouse was ())383940def main():41app QtGui.QApplication(sys.argv)42ex MyForm()43sys.exit(app.exec ())444546if name ' main ':main()4714.6Mouse and Keyboard EventsAnother way to generate events is through the keyboard and mouse. These events can be handled by overriding twomethods defined in the MainForm: mousePressEvent() and keyPressEvent().1# codes 10.

user and the application. This kind of environments are known as a Graphical User Interfaces (GUI). Graphical interfaces are present in various types of devices and platforms, such as web form or a smartphone application. Most, if not all, graphical user interface based applications use an event management based architecture. Applications

Related Documents:

3Dwm: 3D User Interfaces 3Dwm is a platform for building applications with 3D user interfaces 3D user interfaces extends conventional graphical 2D interfaces – Interfaces with ”volume” – Makes use of human spatial perception – Well-suited for Virtual and Augmented Reality – Example: immersive 3D modeller, simulation, 3D

Wizard of Oz, speech user interfaces, prototyping, design, low-fidelity, informal user interfaces, design tools INTRODUCTION Speech-based user interfaces are more appropriate than graphical user interfaces in many settings and thus will

The graphical desktop presents a Graphical User Interface (GUI) for the user to interact with the system and run appl i cto ns. If you hav eus dh x -b r login, you will have to start the graphical desktop manually by entering the command startx followed by the ENTER key. Fig. Starting the Graphical Desktop Note: The graphical desktop that we .

Internal Interfaces behave as regular layer 2 interfaces. No OTV configuration is needed on the OTV Internal Interfaces. Typically these interfaces are configure as Layer 2 trunks carrying the VLANs to be extended across the Overlay. OTV Internal Interface OTV Internal Interfaces OTV Internal Interfaces

Graphical User Interface Programming –GTK SEEM3460/ESTR3504 1. Backgound GTK supports the develop of graphical user interface (GUI) in Linux. GTK was adopted as the default graphical toolkit of GNOME and XFCE, two of the most popular Linux desktop environments. GT

BeSt PrActiceS: KiOSK GrAPHicAL USer iNterFAceS tended use of the kiosk is high, but if the delivery of information leads the user to be frustrated, repeat usage will be low. conclusIon The design process for a self-service interface can be complex. What’s most important is to ensure that the customer will have a positive experience.

Graphical Analysis 4 computer software is free and can be installed on an unlimited amount of computers. Graphical Analysis 4 apps for Chrome, iOS, and Android are free and distributed through their . Go!Temp, and Go! Motion. Graphical Analysis 4 - User Manual 10 Vernier Software & Technology 2. Connect your desired sensor(s) or interface .

Implication zootechnique du menthol cristallisé comme additif. alimentaire chez le poulet de chair. E. AZEROUAL. 1, M. OUKESSOU. 2, K. BOUZOUBAA. 2, A. MESFIOUI. 1, B. BENAZZOUZ & A. OUICHOU (Reçu le 15/04/2012; Accepté le 18/06/2012) Résumé. Le menthol est utilisé pour ses vertus aromatiques, culinaires, cosmétiques et médicinales. Chez l’homme, il est employé contre les . troubles .