PyQt – Layout Management

PyQt – Layout Management ”; Previous Next A GUI widget can be placed inside the container window by specifying its absolute coordinates measured in pixels. The coordinates are relative to the dimensions of the window defined by setGeometry() method. setGeometry() syntax QWidget.setGeometry(xpos, ypos, width, height) In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor. import sys from PyQt4 import QtGui def window(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() b = QtGui.QPushButton(w) b.setText(“Hello World!”) b.move(50,20) w.setGeometry(10,10,300,200) w.setWindowTitle(“PyQt”) w.show() sys.exit(app.exec_()) if __name__ == ”__main__”: window() A PushButton widget is added in the window and placed at a position 50 pixels towards right and 20 pixels below the top left position of the window. This Absolute Positioning, however, is not suitable because of following reasons − The position of the widget does not change even if the window is resized. The appearance may not be uniform on different display devices with different resolutions. Modification in the layout is difficult as it may need redesigning the entire form. PyQt API provides layout classes for more elegant management of positioning of widgets inside the container. The advantages of Layout managers over absolute positioning are − Widgets inside the window are automatically resized. Ensures uniform appearance on display devices with different resolutions. Adding or removing widget dynamically is possible without having to redesign. Here is the list of Classes which we will discuss one by one in this chapter. Sr.No. Classes & Description 1 QBoxLayout QBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally). 2 QGridLayout A GridLayout class object presents with a grid of cells arranged in rows and columns. The class contains addWidget() method. Any widget can be added by specifying the number of rows and columns of the cell. 3 QFormLayout QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. Print Page Previous Next Advertisements ”;

PyQt – Signals and Slots

PyQt – Signals & Slots ”; Previous Next Unlike a console mode application, which is executed in a sequential manner, a GUI based application is event driven. Functions or methods are executed in response to user’s actions like clicking on a button, selecting an item from a collection or a mouse click etc., called events. Widgets used to build the GUI interface act as the source of such events. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function. In PyQt, connection between a signal and a slot can be achieved in different ways. Following are most commonly used techniques − QtCore.QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function) A more convenient way to call a slot_function, when a signal is emitted by a widget is as follows − widget.signal.connect(slot_function) Suppose if a function is to be called when a button is clicked. Here, the clicked signal is to be connected to a callable function. It can be achieved in any of the following two techniques − QtCore.QObject.connect(button, QtCore.SIGNAL(“clicked()”), slot_function) or button.clicked.connect(slot_function) Example In the following example, two QPushButton objects (b1 and b2) are added in QDialog window. We want to call functions b1_clicked() and b2_clicked() on clicking b1 and b2 respectively. When b1 is clicked, the clicked() signal is connected to b1_clicked() function b1.clicked.connect(b1_clicked()) When b2 is clicked, the clicked() signal is connected to b2_clicked() function QObject.connect(b2, SIGNAL(“clicked()”), b2_clicked) Example import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApplication(sys.argv) win = QDialog() b1 = QPushButton(win) b1.setText(“Button1”) b1.move(50,20) b1.clicked.connect(b1_clicked) b2 = QPushButton(win) b2.setText(“Button2”) b2.move(50,50) QObject.connect(b2,SIGNAL(“clicked()”),b2_clicked) win.setGeometry(100,100,200,100) win.setWindowTitle(“PyQt”) win.show() sys.exit(app.exec_()) def b1_clicked(): print “Button 1 clicked” def b2_clicked(): print “Button 2 clicked” if __name__ == ”__main__”: window() The above code produces the following output − Output Button 1 clicked Button 2 clicked Print Page Previous Next Advertisements ”;

PyQt – Database Handling

PyQt – Database Handling ”; Previous Next PyQt API contains an elaborate class system to communicate with many SQL based databases. Its QSqlDatabase provides access through a Connection object. Following is the list of currently available SQL drivers − Sr.No. Driver Type & Description 1 QDB2 IBM DB2 2 QIBASE Borland InterBase Driver 3 QMYSQL MySQL Driver 4 QOCI Oracle Call Interface Driver 5 QODBC ODBC Driver (includes Microsoft SQL Server) 6 QPSQL PostgreSQL Driver 7 QSQLITE SQLite version 3 or above 8 QSQLITE2 SQLite version 2 Example A connection with a SQLite database is established using the static method − db = QtSql.QSqlDatabase.addDatabase(”QSQLITE”) db.setDatabaseName(”sports.db”) Other methods of QSqlDatabase class are as follows − Sr.No. Methods & Description 1 setDatabaseName() Sets the name of the database with which connection is sought 2 setHostName() Sets the name of the host on which the database is installed 3 setUserName() Specifies the user name for connection 4 setPassword() Sets the connection object’s password if any 5 commit() Commits the transactions and returns true if successful 6 rollback() Rolls back the database transaction 7 close() Closes the connection QSqlQuery class has the functionality to execute and manipulate SQL commands. Both DDL and DML type of SQL queries can be executed. The most important method in the class is exec_(), which takes as an argument a string containing SQL statement to be executed. query = QtSql.QSqlQuery() query.exec_(“create table sportsmen(id int primary key, ” “firstname varchar(20), lastname varchar(20))”) The following script creates a SQLite database sports.db with a table of sportsperson populated with five records. from PyQt4 import QtSql, QtGui def createDB(): db = QtSql.QSqlDatabase.addDatabase(”QSQLITE”) db.setDatabaseName(”sports.db”) if not db.open(): QtGui.QMessageBox.critical(None, QtGui.qApp.tr(“Cannot open database”), QtGui.qApp.tr(“Unable to establish a database connection.n” “This example needs SQLite support. Please read ” “the Qt SQL driver documentation for information ” “how to build it.nn” “Click Cancel to exit.”), QtGui.QMessageBox.Cancel) return False query = QtSql.QSqlQuery() query.exec_(“create table sportsmen(id int primary key, ” “firstname varchar(20), lastname varchar(20))”) query.exec_(“insert into sportsmen values(101, ”Roger”, ”Federer”)”) query.exec_(“insert into sportsmen values(102, ”Christiano”, ”Ronaldo”)”) query.exec_(“insert into sportsmen values(103, ”Ussain”, ”Bolt”)”) query.exec_(“insert into sportsmen values(104, ”Sachin”, ”Tendulkar”)”) query.exec_(“insert into sportsmen values(105, ”Saina”, ”Nehwal”)”) return True if __name__ == ”__main__”: import sys app = QtGui.QApplication(sys.argv) createDB() QSqlTableModel class in PyQt is a high-level interface that provides editable data model for reading and writing records in a single table. This model is used to populate a QTableView object. It presents to the user a scrollable and editable view that can be put on any top level window. A QTableModel object is declared in the following manner − model = QtSql.QSqlTableModel() Its editing strategy can be set to any of the following − QSqlTableModel.OnFieldChange All changes will be applied immediately QSqlTableModel.OnRowChange Changes will be applied when the user selects a different row QSqlTableModel.OnManualSubmit All changes will be cached until either submitAll() or revertAll() is called Example In the following example, sportsperson table is used as a model and the strategy is set as − model.setTable(”sportsmen”) model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange) model.select() QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows − view = QtGui.QTableView() view.setModel(model) view.setWindowTitle(title) return view This QTableView object and two QPushButton widgets are added to the top level QDialog window. Clicked() signal of add button is connected to addrow() which performs insertRow() on the model table. button.clicked.connect(addrow) def addrow(): print model.rowCount() ret = model.insertRows(model.rowCount(), 1) print ret The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user. btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row())) The complete code is as follows − import sys from PyQt4 import QtCore, QtGui, QtSql import sportsconnection def initializeModel(model): model.setTable(”sportsmen”) model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange) model.select() model.setHeaderData(0, QtCore.Qt.Horizontal, “ID”) model.setHeaderData(1, QtCore.Qt.Horizontal, “First name”) model.setHeaderData(2, QtCore.Qt.Horizontal, “Last name”) def createView(title, model): view = QtGui.QTableView() view.setModel(model) view.setWindowTitle(title) return view def addrow(): print model.rowCount() ret = model.insertRows(model.rowCount(), 1) print ret def findrow(i): delrow = i.row() if __name__ == ”__main__”: app = QtGui.QApplication(sys.argv) db = QtSql.QSqlDatabase.addDatabase(”QSQLITE”) db.setDatabaseName(”sports.db”) model = QtSql.QSqlTableModel() delrow = -1 initializeModel(model) view1 = createView(“Table Model (View 1)”, model) view1.clicked.connect(findrow) dlg = QtGui.QDialog() layout = QtGui.QVBoxLayout() layout.addWidget(view1) button = QtGui.QPushButton(“Add a row”) button.clicked.connect(addrow) layout.addWidget(button) btn1 = QtGui.QPushButton(“del a row”) btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row())) layout.addWidget(btn1) dlg.setLayout(layout) dlg.setWindowTitle(“Database Demo”) dlg.show() sys.exit(app.exec_()) The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Using Qt Designer

PyQt – Using Qt Designer ”; Previous Next The PyQt installer comes with a GUI builder tool called Qt Designer. Using its simple drag and drop interface, a GUI interface can be quickly built without having to write the code. It is however, not an IDE such as Visual Studio. Hence, Qt Designer does not have the facility to debug and build the application. Creation of a GUI interface using Qt Designer starts with choosing a top level window for the application. You can then drag and drop required widgets from the widget box on the left pane. You can also assign value to properties of widget laid on the form. The designed form is saved as demo.ui. This ui file contains XML representation of widgets and their properties in the design. This design is translated into Python equivalent by using pyuic4 command line utility. This utility is a wrapper for uic module. The usage of pyuic4 is as follows − pyuic4 –x demo.ui –o demo.py In the above command, -x switch adds a small amount of additional code to the generated XML so that it becomes a self-executable standalone application. if __name__ == “__main__”: import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_()) The resultant python script is executed to show the following dialog box − The user can input data in input fields but clicking on Add button will not generate any action as it is not associated with any function. Reacting to user-generated response is called as event handling. Print Page Previous Next Advertisements ”;

PyQt – Hello World

PyQt – Hello World ”; Previous Next Creating a simple GUI application using PyQt involves the following steps − Import QtGui module. Create an application object. A QWidget object creates top level window. Add QLabel object in it. Set the caption of label as “hello world”. Define the size and position of window by setGeometry() method. Enter the mainloop of application by app.exec_() method. import sys from PyQt4 import QtGui def window(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() b = QtGui.QLabel(w) b.setText(“Hello World!”) w.setGeometry(100,100,200,50) b.move(50,20) w.setWindowTitle(“PyQt”) w.show() sys.exit(app.exec_()) if __name__ == ”__main__”: window() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Home

PyQt Tutorial PDF Version Quick Guide Resources Job Search Discussion PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt is a blend of Python programming language and the Qt library. This introductory tutorial will assist you in creating graphical applications with the help of PyQt. Audience This tutorial is designed for software programmers who are keen on learning how to develop graphical applications using PyQt. Prerequisites You should have a basic understanding of computer programming terminologies. A basic understanding of Python and any of the programming languages is a plus. Print Page Previous Next Advertisements ”;

PyQt – Basic Widgets

PyQt – Basic Widgets ”; Previous Next Here is the list of Widgets which we will discuss one by one in this chapter. Sr.No Widgets & Description 1 QLabel A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. 2 QLineEdit QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required. 3 QPushButton In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function. 4 QRadioButton A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class. 5 QCheckBox A rectangular box before the text label appears when a QCheckBox object is added to the parent window. Just as QRadioButton, it is also a selectable button. 6 QComboBox A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item. 7 QSpinBox A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right. 8 QSlider Widget & Signal QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. 9 QMenuBar, QMenu & QAction A horizontal QMenuBar just below the title bar of a QMainWindow object is reserved for displaying QMenu objects. 10 QToolBar A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets. 11 QInputDialog This is a preconfigured dialog with a text field and two buttons, OK and Cancel. The parent window collects the input in the text box after the user clicks on Ok button or presses Enter. 12 QFontDialog Another commonly used dialog, a font selector widget is the visual appearance of QDialog class. Result of this dialog is a Qfont object, which can be consumed by the parent window. 13 QFileDialog This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object. 14 QTab If a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area. 15 QStacked Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area. 16 QSplitter If a form has too many fields to be displayed simultaneously, they can be arranged in different pages placed under each tab of a Tabbed Widget. The QTabWidget provides a tab bar and a page area. 17 QDock A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. 18 QStatusBar QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information. 19 QList QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable. 20 QScrollBar A scrollbar control enables the user to access parts of the document that is outside the viewable area. It provides visual indicator to the current position. 21 QCalendar QCalendar widget is a useful date picker control. It provides a month-based view. The user can select the date by the use of the mouse or the keyboard, the default being today’s date. Print Page Previous Next Advertisements ”;

PyQt – Introduction

PyQt – Introduction ”; Previous Next PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc. Supporting Environments PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license. Windows You can download and install an appropriate installer from the above download link corresponding to Python version (2.7 or 3.4) and hardware architecture (32 bit or 64 bit). Note that there are two versions of PyQt that are available namely, PyQt 4.8 and PyQt 5.5. While PyQt4 is available for Python 2 as well as Python 3, PyQt5 can be used along with Python 3.* only. PyQt4 Windows Binaries PyQt4-4.11.4-gpl-Py3.4-Qt4.8.7-x64.exe Windows 64 bit installer PyQt4-4.11.4-gpl-Py3.4-Qt4.8.7-x32.exe Windows 32 bit installer PyQt4-4.11.4-gpl-Py3.4-Qt5.5.0-x64.exe Windows 64 bit installer PyQt4-4.11.4-gpl-Py3.4-Qt5.5.0-x32.exe Windows 32 bit installer PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x64.exe Windows 64 bit installer PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe Windows 32 bit installer PyQt5 Windows Binaries PyQt5-5.5-gpl-Py3.4-Qt5.5.0-x64.exe Windows 64 bit installer PyQt5-5.5-gpl-Py3.4-Qt5.5.0-x32.exe Windows 32 bit installer Linux For Ubuntu or any other debian Linux distribution, use the following command to install PyQt − sudo apt-get install python-qt4 or sudo apt-get install pyqt5-dev-tools You can also build from the source code available on the ‘download’ page. PyQt-x11-gpl-4.11.4.tar.gz Linux, UNIX source for PyQt4 PyQt-gpl-5.5.tar.gz Linux, UNIX, MacOS/X source for PyQt5 Mac OS PyQtX project (http://sourceforge.net/projects/pyqtx/) hosts binaries of PyQt for Mac. Use Homebrew installer as per the following command − brew install pyqt Print Page Previous Next Advertisements ”;

PyQt – BrushStyle Constants

PyQt – BrushStyle Constants ”; Previous Next Predefined QColor Styles Qt.NoBrush No brush pattern Qt.SolidPattern Uniform color Qt.Dense1Pattern Extremely dense brush pattern Qt.HorPattern Horizontal lines Qt.VerPattern Vertical lines Qt.CrossPattern Crossing horizontal and vertical lines Qt.BDiagPattern Backward diagonal lines Qt.FDiagPattern Forward diagonal lines Qt.DiagCrossPattern Crossing diagonal lines Predefined QColor Objects Qt.white Qt.black Qt.red Qt.darkRed Qt.green Qt.darkGreen Qt.blue Qt.cyan Qt.magenta Qt.yellow Qt.darkYellow Qt.gray Custom color can be chosen by specifying RGB or CMYK or HSV values. Example The following example implements some of these methods. import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.text = “hello world” self.setGeometry(100,100, 400,300) self.setWindowTitle(”Draw Demo”) self.show() def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setPen(QColor(Qt.red)) qp.setFont(QFont(”Arial”, 20)) qp.drawText(10,50, “hello Pyth on”) qp.setPen(QColor(Qt.blue)) qp.drawLine(10,100,100,100) qp.drawRect(10,150,150,100) qp.setPen(QColor(Qt.yellow)) qp.drawEllipse(100,50,100,50) qp.drawPixmap(220,10,QPixmap(“python.jpg”)) qp.fillRect(200,175,150,100,QBrush(Qt.SolidPattern)) qp.end() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == ”__main__”: main() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – QDialog Class

PyQt – QDialog Class ”; Previous Next A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed). PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc. Example In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key. A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar. The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal. import sys from PyQt4.QtGui import * from PyQt4.QtCore import * def window(): app = QApplication(sys.argv) w = QWidget() b = QPushButton(w) b.setText(“Hello World!”) b.move(50,50) b.clicked.connect(showdialog) w.setWindowTitle(“PyQt Dialog demo”) w.show() sys.exit(app.exec_()) def showdialog(): d = QDialog() b1 = QPushButton(“ok”,d) b1.move(50,50) d.setWindowTitle(“Dialog”) d.setWindowModality(Qt.ApplicationModal) d.exec_() if __name__ == ”__main__”: window() The above code produces the following output − Print Page Previous Next Advertisements ”;