Introduction To GUI Programming In Python

2y ago
55 Views
8 Downloads
1.80 MB
58 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Camryn Boren
Transcription

Introduction to GUI programming inPythonAlice Invernizzia.invernizzi@cineca.it

Index Introduction to GUI programming Overview of Qt Framework for Python How to embed matplotlib/vtk widget inside QtGUI

Introduction to GUI GUI (Graphical User Interface)is a type of interface thatallows users to communicatewith eletronic devices usingimages rather than textcommand.A GUI represents theinformation and actionsavailable to a user throughgraphical icons. The actionsare usually performed throughdirect manipulation of thegraphical elements.

Introduction to GUIThe precursor to GUIs was inventedby researchers at the StanfordResearch Institute, led by DouglasEngelbart. They developed the useof text-based hyperlinksmanipulated with a mouse (1963)In 1983, the Apple Lisa was firstGUI offering.

Introduction to GUIThe X Windows System was introducedin the mid-1980s to provide graphicalsupport for unix operating systems.Microsoft introducedA Windows 1.0 in1985The GUIs familiar to most people today are Microsoft Windows,Mac OS X, and the X Window System interfaces for desktop andlaptop computers, and Symbian, BlackBerry OS, Android,Windows Phone, and Apple's iOS for handheld ("smartphone") devices.

GUI programming in PythonPython has a huge number of GUI frameworks (or toolkits) available forit,from Tkinter (traditionally bundled with Python, using Tk) to a number ofother cross-platform solutions, as well as bindings to platform-specifictechnologies.EasyGui: is a module for very simple, very easy GUI programming inPython.Tkinter: standard GUI toolkit included with Python, simple and easyWxPython: xWidgets is a C library that lets developers createapplications for Windows, OS X, Linux and UNIX, with binding for PythonPyQt: Python bindings for the Qt application development framework, not just GUI featuresFor a complete list:http://wiki.python.org/moin/GuiProgramming

Introduction to QtWhat is Qt?Qt is a cross platform development framework written in C .Qt was developed by Trolltech (now owned by Nokia) Though written in C , Qt can also be used in several other programminglanguages, through language bindings available for Ruby, Java, Perl, andalso Python with PyQt. The Qt toolkit is a collection of classes to simplify the creation ofprograms. Qt is more than just a GUI toolkit:Databases, XML, WebKit, multimedia, networking, OpenGL, scripting,non-GUI. Qt is available on several platforms, in particular: Unix/Linux, Windows,Mac OS

Introduction to QtCode less because even the function linkingis drag and drop capable!Create more because you spend less timecoding and more time innovating!Lastly, Deploy Everywhere because it CAN runon any of its supported platforms(Windows, supported Linux, Mac, supported Symbian)without altering the code

Introduction to QtQt is built from modulesAll modules have a common scheme and arebuilt from the same API design ideas

Introduction to QtQtCoreObject and meta-object system:QObject, QMetaObject Basic value types:QByteArray, QString, QDate, QTime, QPoint[F],QSize[F] File system abstraction:QFile, QDir, QIODevice, QTextStream, QDataStream Basic application support:QCoreApplication – encapsulates an applicationQEvent – communication (see also signals and slots)QTimer – signal-based timed event handling

Introduction to QtQtGUI Widgets:QCheckBox, QComboBox, QDateTimeEdit, QLineEdit,QPushButton,QRadioButton, QSlider, QSpinBox, etc. Basic value types:QColor, QFont, QBrush, QPen Painting system and devices:QPainter, QPaintDevice, QPrinter, QImage, QPixmap, QWidget Basic application support:QApplication – encapsulates a GUI application Rich text:QTextEdit, QTextDocument, QTextCursor

QObject ModelThe QObject class is the base class of all Qt objects.QObject is the heart of the Qt Object Model.Three major responsibilities of QObject: Memory ManagementIntrospection (runtime identification of object types)Event handling

Qt Object ModelAll PyQt classes that derive from QObject can have a “parent”.A widget that has no parent is a top-level window, and a widget that has aparent (always another widget) is contained (displayed) within its parent.PyQt uses the parent–child ownership model to ensure that if a parent—forexample, a top-level window—is deleted, all its children, for example, allthe widgets the window contains, are automatically deleted as wellObject Ownership

PyQt Simple ExampleA tiny PyQt applications has the following elements:- an application object- a main window (which has a central widget), or- a main widgetThis is the traditional ”Hello World” application, with as little codeas possible:

PyQt Simple ExampleThe Basic GUI widget are locatedin QtGui moduleimport sysfrom PyQt4 import QtGuiapp QtGui.QApplication(sys.argv)Every PyQt4 application must definewidget QtGui.QWidget()An application object located in QtGuiwidget.resize(250, 150)widget.setWindowTitle('Hello World')widget.show()The QWidget widget is the basesys.exit(app.exec ())class of all user interface objectsin PyQt4Finally, we enter the mainloop of the application. The event handling startsfrom this point. The mainloop receives events from the window system anddispatches them to the application widgets. The mainloop ends, if we callthe exit() method or the main widget is destroyed

GUI ComponentsUser interfaces are built fromindividual widgetsThere are more than 59 direct descendants fromQwidget.

Simple PyQt Exampleimport sysOOP style. QtFramework is anfrom PyQt4 import QtGui, QtCoreframeworkclass QuitButton(QtGui.QWidget):def init (self, parent None):QtGui.QWidget. init (self, parent)self.setGeometry(300, 300, 250, 150)Ownership, parent-childself.setWindowTitle('Simple')quit QtGui.QPushButton('Close', self)quit.setGeometry(10, 10, 60, 35)self.connect(quit, 'quit()'))app QtGui.QApplication(sys.argv)qb QuitButton()qb.show()sys.exit(app.exec ())OO

Simple PyQt Exampleimport sysfrom PyQt4 import QtGui, QtCoreapp QtGui.QApplication(sys.argv)widget et.setGeometry(300, 300, 250, 150)button y(10, 10, 60, 35)app.connect(button, QtCore.SIGNAL('clicked()'),QtGui.qApp, ec ())Connection to manage GUIevents

Layout ManagementImportant thing in programming is the layout management. Layoutmanagement is the way how we place the widgets on the window.The management can be done in two ways. We can use absolutepositioning or layout classes.The programmer specifies the position and the size of each widgetin pixels.NOTES: The size and the position of a widget do not change, if you resizea window Applications might look different on various platforms

Box LayoutLayout management with layout classes is much more flexible and practical. It isthe preferred way to place widgets on a window. The basic layout classes areQHBoxLayout and QVBoxLayout.class BoxLayout(QtGui.QWidget):def init (self, parent None):QtGui.QWidget. init (self, parent)self.setWindowTitle('box layout')ok QtGui.QPushButton("OK")cancel QtGui.QPushButton("Cancel")hbox t(ok)hbox.addWidget(cancel)vbox t(hbox)self.setLayout(vbox)self.resize(300, 150)app QtGui.QApplication(sys.argv)qb BoxLayout()qb.show()sys.exit(app.exec ())

Grid LayoutThe most universal layout class is the grid layout. This layout divides thespace into rows and columns.import sysfrom PyQt4 import QtGUiclass GridLayout(QtGui.QWidget):def init (self, parent None):QtGui.QWidget. init (self, parent)self.setWindowTitle('grid layout')names [ '7', '8', '9', '4', '5', '6']grid QtGui.QGridLayout()j 0pos [(0, 0), (0, 1), (0, 2), (1, 0), (1,1),(1,2)]for i in names:button QtGui.QPushButton(i)grid.addWidget(button, pos[j][0], pos[j][1])j j 1self.setLayout(grid)app QtGui.QApplication(sys.argv)qb GridLayout()qb.show()sys.exit(app.exec ())

Main WindowThe QMainWindow class provides a main application window. This enables tocreate the classic application skeleton with a statusbar, toolbars and amenubar.The statusbar is a widget that is used for displaying status information.import sysfrom PyQt4 import QtGuiclass MainWindow(QtGui.QMainWindow):def init (self):QtGui.QMainWindow. init (self)self.resize(250, ().showMessage('Ready')app QtGui.QApplication(sys.argv)main MainWindow()main.show()sys.exit(app.exec ())

Main Window A menubar is one of the most visible parts of the GUI application.It is a group of commands located in various menus. Toolbars provide a quick access to the most frequently usedcommands. GUI applications are controlled with commands. These commandscan be launched from a menu, a context menu, a toolbar or witha shortcut. PyQt simplifies development with the introduction ofactions. User actions are represented by the QAction class The action system synchronizes menus, toolbars, and keyboardshortcuts, it also stores information about tooltips and interactivehelp

Main WindowMenuBarQActionTo create an action, you can:ToolBar Instantiate a QAction object directly Call addAction() on existing QMenu and QToolBarobjects Then you can share it with other objects.self.saveAction QAction(QIcon(":/images/save.png"), "&Save.",self)self.saveAction.setShortcut("Ctrl S")self.saveAction.setStatusTip("Save the current form letter")self.connect(self.saveAct, QtCore.SIGNAL("triggered()"), self.save).self.fileMenu tion(self.saveAction).self.fileToolBar self.saveAct)

Main WindowWe will create a menubar, toolbar and a statusbar. We will also create a centralwidget.import sysfrom PyQt4 import QtGui, QtCoreclass MainWindow(QtGui.QMainWindow):def init (self):QtGui.QMainWindow. init (self)self.resize(350, 250)self.setWindowTitle('mainwindow')textEdit it QtGui.QAction(QtGui.QIcon(‘\Icon\exit.png'), 'Exit', self)exit.setShortcut('Ctrl Q')exit.setStatusTip('Exit application')self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))self.statusBar()menubar self.menuBar()file r self.addToolBar('Exit')toolbar.addAction(exit)app QtGui.QApplication(sys.argv)main MainWindow()main.show()sys.exit(app.exec ())

Signal and SlotEvents are an important part in any GUI program. Events are generatedby users or by the system. When we call the application's exec ()method, the application enters the main loop. The main loop fetchesevents and sends them to the objects. Trolltech has introduced a uniquesignal and slot mechanism.Signals are emitted, when users click on the button, drag a slider etc.Signals can be emitted also by the environment.A Slot is a method, that reacts to a signal. In python, a slot can be anypython callable.

Signal and Slot

Signal and dest,SLOT(signature))Connections are made using the connect() method.The connect function can take the following parameters:sender — the QObject that will send the signal.signal— the signal that must be connectedreceiver — the QObject that has the slot method that will becalled when the signal is emitted.slot— the slot method that will be called when the signal isemitted.

Signal and Slot In many PyQt code samples the "old-style" signal-slot connectionmechanism is used.from PyQt4.QtCore import *from PyQt4.QtGui import *class MyForm(QMainWindow):def init (self, parent None):QMainWindow. init (self,parent)the button QPushButton(‘Close')Old-style signal/slotself.connect(the button, SIGNAL('clicked()'), self, e button)app QApplication(sys.argv)form MyForm()form.show()app.exec ()

Signal and SlotApart from being verbose and un-Pythonic, this syntax has a serious problem.You must type the C signature of the signal exactly. Otherwise, the signaljust won’t fire, without an exception or any warning. This is a verycommon mistake.The "new-style" signal-slot connection mechanism is much better. Here’s howthe connection is is mechanism is supported by PyQt since version 4.5, and provides asafer and much more convenient way to connect signals and slots. Eachsignal is now an attribute that gets automatically bound once you access it.

Signal and Slotfrom PyQt4.QtCore import *from PyQt4.QtGui import *class MyForm(QMainWindow):def init (self, parent None):super(MyForm, self). init (parent)the button QPushButton(‘Close')the idget(the button)app QApplication(sys.argv)form MyForm()form.show()app.exec ()New-style signal/slotsyntax

Signal and Slot A signal can be connected to any number of slots. In this case, the slotsare activated in arbitrary order. A slot may not have more arguments than the signal that is connected toit. But may have less; the additional parameters are then discarted Corresponding signal and slot arguments must have the sametypes, so for example,we could not connect a QDial’svalueChanged(int) signal to a QLineEdit’s setText(QString)slot. A signal may also be connected to another signal.

Signal and SlotA small example, using built-in signal and slot.from PyQt4 import QtGui, QtCoreimport sysclass Test(QtGui.QWidget):def init (self,parent None):QtGui.QWidget. init (self, etry(300,300,250,150)self.Line QtGui.QLineEdit(' ',self)self.ComboBox )self.ComboBox.addItem('Item2')self.grid tCore.SLOT('setText(QString)'))app QtGui.QApplication(sys.argv)widget Test()widget.setGeometry(300, 300, 250, 150)widget.show()sys.exit(app.exec ())

Signal and SlotA small example, using built-in signal and user-defined slot.from PyQt4 import QtCore, QtGuiclass MyWindow(QtGui.QWidget):def init (self, parent None):super(MyWindow, self). init (parent)self.pushButtonWindow xt("Click Me!")self.pushButtonWindow.clicked.connect(self.on pushButton clicked)self.layout pushButtonWindow)def on pushButton clicked(self):s QtGui.QDialog()button (s.close)s.exec ()app ('MyWindow')main MyWindow()main.show()sys.exit(app.exec ())

Signal and SlotA small example, using user-defined signal and user-defined slot.from PyQt4 import QtGui, QtCoreclass MyWidget(QtGui.QWidget):mysignal QtCore.pyqtSignal( list)def init (self, parent None):QtGui.QWidget. init (self,parent)self.button QtGui.QPushButton("OK", self)self.text QtGui.QLineEdit()self.spin QtGui.QSpinBox()self.grid gnal.connect(self.OnPrint)

Signal and Slotdef OnClicked(self):val l'),range(val))self.mysignal.emit(range(val))def OnPrint(self,val):s ' 'for el in val:s str(el) ' 'self.text.setText(s)if name ' main ':import sysapp QtGui.QApplication(sys.argv)w MyWidget()w.show()sys.exit(app.exec ())Change Value in SpinBox, pressbutton Ok. LineEdit will be modifieddepending on the value of SpinBox

Dialogs in PyQtDialog windows or dialogs are an indispensable part of most modern GUIapplications.In a computer application a dialog is a window which is used to "talk" to theapplication. A dialog is used to input data, modify data, change theapplication settings etc.Dialogs are important means of communication between a user and acomputer program.There are essentially two types of dialogs. Predefined dialogs and customdialogs.

Dialogs in PyQt Predefined dialogs inheritsfrom a general base QDialog widget. Common dialog widget are:QFileDialogQInputDialogQFontDialog Customized widget can be inheritedfrom QDialog or from one of its specialization.

Example: QFileDialogimport sysfrom PyQt4 import QtGuifrom PyQt4 import QtCoreclass OpenFile(QtGui.QMainWindow):def init (self, parent None):QtGui.QMainWindow. init (self, parent)self.setGeometry(300, 300, 350, 300)self.setWindowTitle('OpenFile')self.textEdit it)self.statusBar()self.setFocus()exit QtGui.QAction(QtGui.QIcon('open.png'), 'Open', self)exit.setShortcut('Ctrl O')exit.setStatusTip('Open new File')self.connect(exit, QtCore.SIGNAL('triggered()'), self.showDialog)

Example: QFileDialogmenubar self.menuBar()file menubar.addMenu('&File')file.addAction(exit)def showDialog(self):filename QtGui.QFileDialog.getOpenFileName(self, 'Open file','/home')file open(filename)data file.read()self.textEdit.setText(data)app QtGui.QApplication(sys.argv)cd OpenFile()cd.show()app.exec ()

Example: Custom Dialogclass Form(QDialog):changed pyqtSignal(QString)def init (self, parent None):super(Form, self). init (parent)self.browser QTextBrowser()self.lineedit QLineEdit("Type an expression and press Enter")self.lineedit.selectAll()layout wTitle("Calculate")def updateUi(self):try:text %s b %s /b " % (text, lf.lineedit.text())except:self.browser.append(" font color red %s is invalid! /font " %text)

Example: Custom Dialogclass MainWindow(QtGui.QWidget):def init (self):QtGui.QWidget. init (self)self.resize(350, 250)self.setWindowTitle('mainwindow')self.label QtGui.QLabel('Var ',self)self.line QtGui.QLineEdit('',self)self.button QtGui.QPushButton('Calculator',self)self.layoutH f.layoutH.addWidget(self.line)self.layoutV g)def Dialog(self):diag Form()diag.changed.connect(self.Update)diag.exec ()def Update(self,stringa):self.line.setText(stringa)

MessageBoxSometimes it is necessary to show a message to confirm some actionimport sysfrom PyQt4 import QtGuiclass MessageBox(QtGui.QMainWindow):def init (self, parent None):QtGui.QMainWindow. init (self, parent)self.setGeometry(300, 300, 250, 150)self.setWindowTitle('message box')self.button ef closeEvent(self, event):reply QtGui.QMessageBox.question(self, 'Message',"Are you sure to if reply ore()app QtGui.QApplication(sys.argv)qb MessageBox()qb.show()sys.exit(app.exec ())

Building GUI using QtDesignerQt Designer is the Qt tool for designing and building graphical user interfaces.It allows you to design widgets, dialogs or complete main windows usingon-screen forms and a simple drag-and-drop interface.It has the ability to preview your designs to ensure they work as you intended.

Building GUI using QtDesignerQt Designer uses XML .ui

GUI programming in Python Python has a huge number of GUI frameworks (or toolkits) available for it,from Tkinter (traditionally bundled with Python, using Tk) to a number of other cross-platform solutions, as well as bindings to platform-specific technologies. EasyGui: is a module for very simp

Related Documents:

layout and the components of the GUI Changes to this file are made in the Layout Editor - .m file - contains the code that controls the GUI You can program the callbacks in this file using the M-file Editor 28 Creating a GUI Typical stages of creating a GUI are: 1. Designing the GUI 2. Laying out the GUI - Using the Layout Editor 3.

In Java, GUI programming is object-oriented programming. This chapter covers the basics of GUI programming. The discussion will continue in Chap-ter 12 with more details and with more advanced techniques. 6.1 The Basic GUI Application There are two basic types of GUI program in Java: stand-alone applications and applets.

User Interface Programming in C#: Basics and Events Chris North CS 3724: HCI GUI Development: Goals 1. General GUI pro grammin concepts GUI components, layouts Event-based programming Graphics D irec tM a npul o,Am MVC architectures Data-driven UIs 2. C#, .NET Windows Forms Events, delegates GDI Threads .

Java GUI libraries Swing: the main Java GUI library – Benefits: Features; cross-platform compatibility; OO design – Paints GUI controls itself pixel-by-pixel Does not delegate to OS’s window system Abstract Windowing Toolkit (AWT): Sun's initial GUI library – Maps Java code to each operating system's real GUI system

No change in API which Apps refer to Apps can use API of each GUI-lib. Each GUI-lib has layer to adapt to PF Can have many different GUI-libs without change of PF. HMI Apps App FW Layer Service Layer AppLayer GUI-library GUI-lib PAL(*) ForAGL PF *PF Adaptation Layer HMI-Server (e.g.

the GUI toolkit for Tcl/Tk. Tcl (pronounced "tickle" and is an acronym for Tool Command Language) is a popular scripting language in the domains of embedded applications, testing, prototyping, and GUI development. Tk on the other hand is an open source, multiplatform widget toolkit that is used by many different languages for building GUI programs.

Programming a GUIDE GUI.2-8 About the Simple GUIDE GUI Example.2-9 Simple GUIDE GUI Components.2-9 View Simple GUIDE GUI Layout and Code File . Designing for Cross-Platform Compatibility.6-137 Default System Font.6-137 viii Contents. Standard Background .

GUI‐related classes are defined primarily in the java.awt and the javax.swingpackages The Abstract Windowing Toolkit(AWT) was the original Java GUI package The Swing package provides additional and more versatile components Both packages are needed to create a Java GUI‐based program SEEM 3460 3