PyQt – QMessageBox

PyQt – QMessageBox ”; Previous Next QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number. Important methods and enumerations associated with QMessageBox class are given in the following table − Sr.No. Methods & Description 1 setIcon() Displays predefined icon corresponding to severity of the message Question Information Warning Critical 2 setText() Sets the text of the main message to be displayed 3 setInformativeText() Displays additional information 4 setDetailText() Dialog shows a Details button. This text appears on clicking it 5 setTitle() Displays the custom title of dialog 6 setStandardButtons() List of standard buttons to be displayed. Each button is associated with QMessageBox.Ok 0x00000400 QMessageBox.Open 0x00002000 QMessageBox.Save 0x00000800 QMessageBox.Cancel 0x00400000 QMessageBox.Close 0x00200000 QMessageBox.Yes 0x00004000 QMessageBox.No 0x00010000 QMessageBox.Abort 0x00040000 QMessageBox.Retry 0x00080000 QMessageBox.Ignore 0x00100000 7 setDefaultButton() Sets the button as default. It emits the clicked signal if Enter is pressed 8 setEscapeButton() Sets the button to be treated as clicked if the escape key is pressed Example In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog. msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText(“This is a message box”) msg.setInformativeText(“This is additional information”) msg.setWindowTitle(“MessageBox demo”) msg.setDetailedText(“The details are as follows:”) setStandardButton() function displays desired buttons. msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal. msg.buttonClicked.connect(msgbtn) The complete code for the example is as follows − import sys from PyQt4.QtGui import * from PyQt4.QtCore import * def window(): app = QApplication(sys.argv) w = QWidget() b = QPushButton(w) b.setText(“Show message!”) b.move(50,50) b.clicked.connect(showdialog) w.setWindowTitle(“PyQt Dialog demo”) w.show() sys.exit(app.exec_()) def showdialog(): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText(“This is a message box”) msg.setInformativeText(“This is additional information”) msg.setWindowTitle(“MessageBox demo”) msg.setDetailedText(“The details are as follows:”) msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msg.buttonClicked.connect(msgbtn) retval = msg.exec_() print “value of pressed message box button:”, retval def msgbtn(i): print “Button pressed is:”,i.text() if __name__ == ”__main__”: window() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Major Classes

PyQt – Major Classes ”; Previous Next PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules. Following are some of the frequently used modules − Sr.No. Modules & Description 1 QtCore Core non-GUI classes used by other modules 2 QtGui Graphical user interface components 3 QtMultimedia Classes for low-level multimedia programming 4 QtNetwork Classes for network programming 5 QtOpenGL OpenGL support classes 6 QtScript Classes for evaluating Qt Scripts 7 QtSql Classes for database integration using SQL 8 QtSvg Classes for displaying the contents of SVG files 9 QtWebKit Classes for rendering and editing HTML 10 QtXml Classes for handling XML 11 QtAssistant Support for online help 12 QtDesigner Classes for extending Qt Designer PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can be painted. QApplication class manages the main settings and control flow of a GUI application. It contains main event loop inside which events generated by window elements and other sources are processed and dispatched. It also handles system-wide and application-wide settings. QWidget class, derived from QObject and QPaintDevice classes is the base class for all user interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their own sub-class system. Following diagrams depict some important classes in their hierarchy. Here is a select list of frequently used widgets − Given below are the commonly used Widgets. Sr.No. Widgets & Description 1 QLabel Used to display text or image 2 QLineEdit Allows the user to enter one line of text 3 QTextEdit Allows the user to enter multi-line text 4 QPushButton A command button to invoke action 5 QRadioButton Enables to choose one from multiple options 6 QCheckBox Enables choice of more than one options 7 QSpinBox Enables to increase/decrease an integer value 8 QScrollBar Enables to access contents of a widget beyond display aperture 9 QSlider Enables to change the bound value linearly. 10 QComboBox Provides a dropdown list of items to select from 11 QMenuBar Horizontal bar holding QMenu objects 12 QStatusBar Usually at bottom of QMainWindow, provides status information. 13 QToolBar Usually at top of QMainWindow or floating. Contains action buttons 14 QListView Provides a selectable list of items in ListMode or IconMode 15 QPixmap Off-screen image representation for display on QLabel or QPushButton object 16 QDialog Modal or modeless window which can return information to parent window A typical GUI based application’s top level window is created by QMainWindow widget object. Some widgets as listed above take their appointed place in this main window, while others are placed in the central widget area using various layout managers. The following diagram shows the QMainWindow framework − Print Page Previous Next Advertisements ”;

PyQt – QClipboard

PyQt – QClipboard ”; Previous Next The QClipboard class provides access to system-wide clipboard that offers a simple mechanism to copy and paste data between applications. Its action is similar to QDrag class and uses similar data types. QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard. Following are the clipboard class methods that are commonly used − Sr.No. Methods & Description 1 clear() Clears clipboard contents 2 setImage() Copies QImage into clipboard 3 setMimeData() Sets MIME data into clipboard 4 setPixmap() Copies Pixmap object in clipboard 5 setText() Copies QString in clipboard 6 text() Retrieves text from clipboard Signal associated with clipboard object is − Sr.No. Method & Description 1 dataChanged() Whenever clipboard data changes Example In the following example, two TextEdit objects and two Pushbuttons are added to a top level window. To begin with the clipboard object is instantiated. Copy() method of textedit object copies the data onto the system clipboard. When the Paste button is clicked, it fetches the clipboard data and pastes it in other textedit object. Print Page Previous Next Advertisements ”;

PyQt – Quick Guide

PyQt – Quick Guide ”; Previous Next PyQt – Introduction 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 PyQt – Hello World 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 − PyQt – Major Classes PyQt API is a large collection of classes and methods. These classes are defined in more than 20 modules. Following are some of the frequently used modules − Sr.No. Modules & Description 1 QtCore Core non-GUI classes used by other modules 2 QtGui Graphical user interface components 3 QtMultimedia Classes for low-level multimedia programming 4 QtNetwork Classes for network programming 5 QtOpenGL OpenGL support classes 6 QtScript Classes for evaluating Qt Scripts 7 QtSql Classes for database integration using SQL 8 QtSvg Classes for displaying the contents of SVG files 9 QtWebKit Classes for rendering and editing HTML 10 QtXml Classes for handling XML 11 QtAssistant Support for online help 12 QtDesigner Classes for extending Qt Designer PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can be painted. QApplication class manages the main settings and control flow of a GUI application. It contains main event loop inside which events generated by window elements and other sources are processed and dispatched. It also handles system-wide and application-wide settings. QWidget class, derived from QObject and QPaintDevice classes is the base class for all user interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their own sub-class system. Following diagrams depict some important classes in their hierarchy. Here is a select list of frequently used widgets − Given below are the commonly used Widgets. Sr.No. Widgets & Description 1 QLabel Used to display text or image 2 QLineEdit Allows the user to enter one line of text 3 QTextEdit Allows the user to enter multi-line text 4 QPushButton A command button to invoke action 5 QRadioButton Enables to choose one from multiple options 6 QCheckBox Enables choice of more than one options 7 QSpinBox Enables to increase/decrease an integer value 8 QScrollBar Enables to access contents of a widget beyond display aperture 9 QSlider Enables to change the bound value linearly. 10 QComboBox Provides a dropdown list of items to select from 11 QMenuBar Horizontal bar holding QMenu objects 12 QStatusBar Usually at bottom of QMainWindow, provides status information. 13 QToolBar Usually at top of QMainWindow or floating. Contains action buttons 14 QListView Provides a selectable list of items in ListMode or IconMode 15 QPixmap Off-screen image representation for display on QLabel or QPushButton object 16 QDialog Modal or modeless window which can return information to parent window A typical GUI based application’s top level window is created by QMainWindow widget object. Some widgets as listed above take their appointed place in this main window, while others are placed in the central widget area using various layout managers. The following diagram shows the QMainWindow framework − PyQt – Using Qt Designer 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

PyQt – Drag and Drop

PyQt – Drag & Drop ”; Previous Next The provision of drag and drop is very intuitive for the user. It is found in many desktop applications where the user can copy or move objects from one window to another. MIME based drag and drop data transfer is based on QDrag class. QMimeData objects associate the data with their corresponding MIME type. It is stored on clipboard and then used in the drag and drop process. The following QMimeData class functions allow the MIME type to be detected and used conveniently. Tester Getter Setter MIME Types hasText() text() setText() text/plain hasHtml() html() setHtml() text/html hasUrls() urls() setUrls() text/uri-list hasImage() imageData() setImageData() image/ * hasColor() colorData() setColorData() application/x-color Many QWidget objects support the drag and drop activity. Those that allow their data to be dragged have setDragEnabled() which must be set to true. On the other hand, the widgets should respond to the drag and drop events in order to store the data dragged into them. DragEnterEvent provides an event which is sent to the target widget as dragging action enters it. DragMoveEvent is used when the drag and drop action is in progress. DragLeaveEvent is generated as the drag and drop action leaves the widget. DropEvent, on the other hand, occurs when the drop is completed. The event’s proposed action can be accepted or rejected conditionally. Example In the following code, the DragEnterEvent verifies whether the MIME data of the event contains text. If yes, the event’s proposed action is accepted and the text is added as a new item in the ComboBox. import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class combo(QComboBox): def __init__(self, title, parent): super(combo, self).__init__( parent) self.setAcceptDrops(True) def dragEnterEvent(self, e): print e if e.mimeData().hasText(): e.accept() else: e.ignore() def dropEvent(self, e): self.addItem(e.mimeData().text()) class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): lo = QFormLayout() lo.addRow(QLabel(“Type some text in textbox and drag it into combo box”)) edit = QLineEdit() edit.setDragEnabled(True) com = combo(“Button”, self) lo.addRow(edit,com) self.setLayout(lo) self.setWindowTitle(”Simple drag & drop”) def main(): app = QApplication(sys.argv) ex = Example() ex.show() app.exec_() if __name__ == ”__main__”: main() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Discussion

Discuss PyQt ”; 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 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. Print Page Previous Next Advertisements ”;

PyQt – Multiple Document Interface

PyQt – Multiple Document Interface ”; Previous Next A typical GUI application may have multiple windows. Tabbed and stacked widgets allow to activate one such window at a time. However, many a times this approach may not be useful as view of other windows is hidden. One way to display multiple windows simultaneously is to create them as independent windows. This is called as SDI (single Document Interface). This requires more memory resources as each window may have its own menu system, toolbar, etc. MDI (Multiple Document Interface) applications consume lesser memory resources. The sub windows are laid down inside main container with relation to each other. The container widget is called QMdiArea. QMdiArea widget generally occupies the central widget of QMainWondow object. Child windows in this area are instances of QMdiSubWindow class. It is possible to set any QWidget as the internal widget of subWindow object. Sub-windows in the MDI area can be arranged in cascaded or tile fashion. The following table lists important methods of QMdiArea class and QMdiSubWindow class − Sr.No. Methods & Description 1 addSubWindow() Adds a widget as a new subwindow in MDI area 2 removeSubWindow() Removes a widget that is internal widget of a subwindow 3 setActiveSubWindow() Activates a subwindow 4 cascadeSubWindows() Arranges subwindows in MDiArea in a cascaded fashion 5 tileSubWindows() Arranges subwindows in MDiArea in a tiled fashion 6 closeActiveSubWindow() Closes the active subwindow 7 subWindowList() Returns the list of subwindows in MDI Area 8 setWidget() Sets a QWidget as an internal widget of a QMdiSubwindow instance QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object. Example In the following example, top level window comprising of QMainWindow has a menu and MdiArea. self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu(“File”) file.addAction(“New”) file.addAction(“cascade”) file.addAction(“Tiled”) Triggered() signal of the menu is connected to windowaction() function. file.triggered[QAction].connect(self.windowaction) The new action of menu adds a subwindow in MDI area with a title having an incremental number to it. MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle(“subwindow”+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively. The complete code is as follows − import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MainWindow(QMainWindow): count = 0 def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.mdi = QMdiArea() self.setCentralWidget(self.mdi) bar = self.menuBar() file = bar.addMenu(“File”) file.addAction(“New”) file.addAction(“cascade”) file.addAction(“Tiled”) file.triggered[QAction].connect(self.windowaction) self.setWindowTitle(“MDI demo”) def windowaction(self, q): print “triggered” if q.text() == “New”: MainWindow.count = MainWindow.count+1 sub = QMdiSubWindow() sub.setWidget(QTextEdit()) sub.setWindowTitle(“subwindow”+str(MainWindow.count)) self.mdi.addSubWindow(sub) sub.show() if q.text() == “cascade”: self.mdi.cascadeSubWindows() if q.text() == “Tiled”: self.mdi.tileSubWindows() def main(): app = QApplication(sys.argv) ex = MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == ”__main__”: main() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Drawing API

PyQt – Drawing API ”; Previous Next All the QWidget classes in PyQt are sub classed from QPaintDevice class. A QPaintDevice is an abstraction of two dimensional space that can be drawn upon using a QPainter. Dimensions of paint device are measured in pixels starting from the top-left corner. QPainter class performs low level painting on widgets and other paintable devices such as printer. Normally, it is used in widget’s paint event. The QPaintEvent occurs whenever the widget’s appearance is updated. The painter is activated by calling the begin() method, while the end() method deactivates it. In between, the desired pattern is painted by suitable methods as listed in the following table. Sr.No. Methods & Description 1 begin() Starts painting on the target device 2 drawArc() Draws an arc between the starting and the end angle 3 drawEllipse() Draws an ellipse inside a rectangle 4 drawLine() Draws a line with endpoint coordinates specified 5 drawPixmap() Extracts pixmap from the image file and displays it at the specified position 6 drwaPolygon() Draws a polygon using an array of coordinates 7 drawRect() Draws a rectangle starting at the top-left coordinate with the given width and height 8 drawText() Displays the text at given coordinates 9 fillRect() Fills the rectangle with the QColor parameter 10 setBrush() Sets a brush style for painting 11 setPen() Sets the color, size and style of pen to be used for drawing Print Page Previous Next Advertisements ”;

PyQt – QPixmap Class

PyQt – QPixmap Class ”; Previous Next QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button. Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible. The types of image files that can be read into a QPixmap object are as follows − BMP Windows Bitmap GIF Graphic Interchange Format (optional) JPG Joint Photographic Experts Group JPEG Joint Photographic Experts Group PNG Portable Network Graphics PBM Portable Bitmap PGM Portable Graymap PPM Portable Pixmap XBM X11 Bitmap XPM X11 Pixmap Following methods are useful in handling QPixmap object − Sr.No. Methods & Description 1 copy() Copies pixmap data from a QRect object 2 fromImage() Converts QImage object into QPixmap 3 grabWidget() Creates a pixmap from the given widget 4 grabWindow() Create pixmap of data in a window 5 Load() Loads an image file as pixmap 6 save() Saves the QPixmap object as a file 7 toImage Converts a QPixmap to QImage The most common use of QPixmap is to display image on a label/button. Example The following example shows an image displayed on a QLabel by using the setPixmap() method. The complete code is as follows − import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApplication(sys.argv) win = QWidget() l1 = QLabel() l1.setPixmap(QPixmap(“python.jpg”)) vbox = QVBoxLayout() vbox.addWidget(l1) win.setLayout(vbox) win.setWindowTitle(“QPixmap Demo”) win.show() sys.exit(app.exec_()) if __name__ == ”__main__”: window() The above code produces the following output − Print Page Previous Next Advertisements ”;

PyQt – Useful Resources

PyQt – Useful Resources ”; Previous Next The following resources contain additional information on PyQt. Please use them to get more in-depth knowledge on this. Useful Video Courses Python – OpenCV & PyQT5 together 51 Lectures 8 hours Nico @softcademy More Detail Python – The complete guide in 2021 104 Lectures 14.5 hours Nico @softcademy More Detail Python PyQt5 and Qt Creator Course Most Popular 146 Lectures 22.5 hours ALAA EID More Detail Python PyQt5 und Qt Creator Kurs 170 Lectures 28 hours ALAA EID More Detail Full YOLOv4 Pro Course Bundle 51 Lectures 4.5 hours Packt Publishing More Detail Print Page Previous Next Advertisements ”;