Pyqt Simple Menu App Windows And Mac

Mar-30-2017, 06:57 PM (This post was last modified: Mar-30-2017, 06:57 PM by danboid.)
I am trying to package my PyQt based image viewer, shufti, for macOS but I've not had much luck so far. It runs fine from the terminal (if you have Python 3 and PyQt installed already) and I have already successfully packaged it for Windows using cx_freeze so I was hoping it would be as easy under OSX - nope. I have got a MacPorts version of cx_freeze to spit out a binary but its only a few MB in size when I'd be expecting something closer to 80 MB like the Windows build as it is having to bundle most of python 3, Qt and PyQt. When I run it (from the terminal with open -a) I get a very vague error before being dumped to a (Xcode?) debugger of which I havent got a clue how to use, never having done any OSX dev.
I have found a guide on (I'm not allowed to post links yet) called 'Distributing your application on OSX' but its quite outdated, following it hasn't worked for me and the author hasn't replied to my email. Nor has the cx_freeze dev, which is a bit concerning but he may just be busy?
My main questions are:
1 - Is cx_freeze the best tool for the job under macOS?
2 - Does cx_freeze work under Sierra?
3 - Do I have to use a specific version of python, PyQt and/or cx_freeze for this to work? Using macports builds of all the python components seems to be the way t go but this requirement is entirely missing from the official cx_freeze docs.
4 - Will the binary work on OSX Intel 10.6+ or will it be Sierra+ only if I build it under Sierra?
Any tips that anyone has on how to bundle and debug pyqt apps for macOS will be greatly appreciated.
Please be aware that shufti is not only my first ever PyQt app, its also the first ever Python app I've written so please go easy on me if you find it on github!
  1. Pyqt5 Qlabel Click
  2. Pyqt Simple Menu App Windows And Mac 10

The menu bar is a common component of GUI applications. He is a group of commands located on multiple menus. Mac OS treats menu bars differently. To get similar output, we can add the following line: menubar. SetNativeMenubar (False).). 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. The latest stable version is PyQt5-5.13.2. Windows Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later.

Possibly Related Threads…
ThreadAuthorRepliesViewsLast Post
macOS GUIpythonnewbi51,341Jul-05-2020, 03:56 PM
Last Post: ndc85430
[Tkinter] macOS Catalina and Python menu issueSouthernYankee74,044Dec-11-2019, 02:02 AM
Last Post: chrstphrchvz
[Tkinter] Image with pillow on macos not showingrhoekstra32,169May-04-2019, 11:48 PM
Last Post: Larz60+
Packaging VTK and ITK for macOSsandrider01,191Nov-01-2018, 05:24 AM
Last Post: sandrider
About Dialog in PyQt5 on macOScpuin01,722Jan-23-2018, 08:50 PM
Last Post: cpuin
[WxPython] Issues with Exe generation and Packaging dependenciesRavikumar11,672Nov-23-2017, 12:53 PM
Last Post: metulburr
Users browsing this thread: 1 Guest(s)
Pyqt5 right click menu
  • PyQt5 Tutorial
  • PyQt5 Useful Resources
  • Selected Reading

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 −

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.

A list of frequently used modules is given below −

  • QtCore − Core non-GUI classes used by other modules

  • QtGui − Graphical user interface components

  • QtMultimedia − Classes for low-level multimedia programming

  • QtNetwork − Classes for network programming

  • QtOpenGL − OpenGL support classes

  • QtScript − Classes for evaluating Qt Scripts

  • QtSql − Classes for database integration using SQL

  • QtSvg − Classes for displaying the contents of SVG files

  • QtWebKit − Classes for rendering and editing HTML

  • QtXml − Classes for handling XML

  • QtWidgets − Classes for creating classic desktop-style UIs

  • QtDesigner − Classes for extending Qt Designer

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. The latest stable version is PyQt5-5.13.2.


Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later. The recommended way to install is using PIP utility −

To install development tools such as Qt Designer to support PyQt5 wheels, following is the command −

You can also build PyQt5 on Linux/macOS from the source code

PyQt5 API is not automatically compatible with earlier versions. Hence, Python code involving PyQt4 modules should be upgraded manually by making relevant changes. In this chapter, main differences between PyQt4 and PyQt5 have been listed.

PyQt5 is not supported on versions of Python earlier than v2.6.

PyQt5 doesn't support connect() method of QObject class for connection between signal and slot. Hence the usage can no more be implemented −

Only the following syntax is defined −

Classes defined in earlier QtGui module have been distributed in QtGui, QtPrintSupport an QtWidgets modules.

In the new QFileDialog class, The getOpenFileNameAndFilter() method is replaced by getOpenFileName(), getOpenFileNamesAndFilter() by getOpenFileNames() and getSaveFileNameAndFilter() by getSaveFileName(). Older signatures of these methods also have changed.

PyQt5 doesn’t have provision to define a class that is sub-classed from more than one Qt class.

pyuic5 utility (to generates Python code from Designer's XML file) does not support the --pyqt3-wrapper flag.

pyrcc5 does not support the -py2 and -py3 flags. The output of pyrcc5 is compatible with all versions of Python v2.6 onwards.

PyQt5 always invokes sip.setdestroyonexit() automatically and calls the C++ destructor of all wrapped instances that it owns.

Creating a simple GUI application using PyQt involves the following steps −

  • Import QtCore, QtGui and QtWidgets modules from PyQt5 package.

  • Create an application object of QApplication class.

  • 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.

Following is the code to execute Hello World program in PyQt −

The above code produces the following output −

It is also possible to develop an object oriented solution of the above code.

  • Import QtCore, QtGui and QtWidgets modules from PyQt5 package.

  • Create an application object of QApplication class.

  • Declare window class based on QWidget class

  • Add a QLabel object and 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.

Following is the complete code of the object oriented solution −

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


Core non-GUI classes used by other modules



Graphical user interface components



Classes for low-level multimedia programming



Classes for network programming



OpenGL support classes



Classes for evaluating Qt Scripts



Classes for database integration using SQL



Classes for displaying the contents of SVG files



Classes for rendering and editing HTML



Classes for handling XML



Classes for creating classic desktop-style UIs.



Classes for extending Qt Designer



Support for online help

PyQt5 development tools is a collection of useful utilities for Qt development. Following is a select list of such utilities −

Sr.No.Tool Name & Description


Qt Assistant documentation tool



Qt Designer GUI layout tool



Qt Linguist translation tool



compile ts files to qm files



extract translation strings and generate or update ts files



Qt software build tool



QML file viewer



QML file viewer



Qt resource file compiler



Qt User Interface Compiler for generating code from ui files



running unit tests on QML code



command-line tool to list D-Bus services



documentation generator for software projects.



generating and viewing Qt help files.



parses and reports on QML imports

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.

Here is a select list of frequently used widgets

Sr.No.Widgets & Description


Used to display text or image



Allows the user to enter one line of text



Allows the user to enter multi-line text



A command button to invoke action



Enables to choose one from multiple options



Enables choice of more than one options



Enables to increase/decrease an integer value



Enables to access contents of a widget beyond display aperture



Enables to change the bound value linearly.



Provides a dropdown list of items to select from



Horizontal bar holding QMenu objects



Usually at bottom of QMainWindow, provides status information.



Usually at top of QMainWindow or floating. Contains action buttons



Provides a selectable list of items in ListMode or IconMode



Off-screen image representation for display on QLabel or QPushButton object



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 −

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.

Start Qt Designer application which is a part of development tools and installed in scripts folder of the virtual environment.

Start designing GUI interface by choosing File → New menu.

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 pyuic5 command line utility. This utility is a wrapper for uic module of Qt toolkit. The usage of pyuic5 is as follows −

In the above command, -x switch adds a small amount of additional code to the generated Python script (from XML) so that it becomes a self-executable standalone application.

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.

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.

Using Qt Designer's Signal/Slot Editor

First design a simple form with a LineEdit control and a PushButton.

It is desired that if button is pressed, contents of text box should be erased. The QLineEdit widget has a clear() method for this purpose. Hence, the button’s clicked signal is to be connected to clear() method of the text box.

To start with, choose Edit signals/slots from Edit menu (or press F4). Then highlight the button with mouse and drag the cursor towards the textbox

As the mouse is released, a dialog showing signals of button and methods of slot will be displayed. Select clicked signal and clear() method

The Signal/Slot Editor window at bottom right will show the result −

Save ui and Build and Python code from ui file as shown in the below code −

Generated Python code will have the connection between signal and slot by the following statement −

Run and enter some text in the LineEdit. The text will be cleared if the button is pressed.

Building Signal-slot Connection

Instead of using Designer, you can directly establish signal-slot connection by following syntax −

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 technique −


Pyqt5 Qlabel Click

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 −

When b2 is clicked, the clicked() signal is connected to b2_clicked() function.

The above code produces the following output −


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

In the following code snippet, the top level window of 300 by 200 pixels dimensions is displayed at position (10, 10) on the monitor.

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.

Qt toolkit defines various layouts that can be used with Qt Designer utility.

Here is the list of Classes which we will discuss one by one in this chapter.

Sr.No.Classes & Description

QBoxLayout class lines up the widgets vertically or horizontally. Its derived classes are QVBoxLayout (for arranging widgets vertically) and QHBoxLayout (for arranging widgets horizontally).


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.


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.

Here is the list of Widgets which we will discuss one by one in this chapter.

Sr.NoWidgets & Description

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.


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.


In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function.


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.


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.


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.


A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right.

8QSlider 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.

9QMenuBar, QMenu & QAction

A horizontal QMenuBar just below the title bar of a QMainWindow object is reserved for displaying QMenu objects.


A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets.


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.


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.


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.


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.


Functioning of QStackedWidget is similar to QTabWidget. It also helps in the efficient use of window’s client area.


This is another advanced layout manager which allows the size of child widgets to be changed dynamically by dragging the boundaries between them. The Splitter control provides a handle that can be dragged to resize the controls.


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.


QMainWindow object reserves a horizontal bar at the bottom as the status bar. It is used to display either permanent or contextual status information.


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.


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.


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.

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.


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.

The above code produces the following output. Click on button in main window and dialog box pops up −

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


Displays predefined icon corresponding to severity of the message

  • Question
  • Information
  • Warning
  • Critical


Sets the text of the main message to be displayed



Displays additional information



Dialog shows a Details button. This text appears on clicking it



Displays the custom title of dialog



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



Sets the button as default. It emits the clicked signal if Enter is pressed



Sets the button to be treated as clicked if the escape key is pressed


In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog.

Pyqt Simple Menu App Windows And Mac 10

setStandardButton() function displays desired buttons.

buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal.

The complete code for the example is as follows −

The above code produces the following output. Message Box pops up when main windows’ button is clicked −

If you click on Ok or Cancel button on MessageBox, the following output is produced on the console −

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


Adds a widget as a new subwindow in MDI area



Removes a widget that is internal widget of a subwindow



Activates a subwindow



Arranges subwindows in MDiArea in a cascaded fashion



Arranges subwindows in MDiArea in a tiled fashion



Closes the active subwindow



Returns the list of subwindows in MDI Area



Sets a QWidget as an internal widget of a QMdiSubwindow instance

QMdiArea object emits subWindowActivated() signal whereas windowStateChanged() signal is emitted by QMdisubWindow object.


In the following example, top level window comprising of QMainWindow has a menu and MdiArea.

Triggered() signal of the menu is connected to windowaction() function.

The new action of menu adds a subwindow in MDI area with a title having an incremental number to it.

Cascaded and tiled buttons of the menu arrange currently displayed subwindows in cascaded and tiled fashion respectively.

The complete code is as follows −

Run above code and three windows in cascased and tiled formation −

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.

TesterGetterSetterMIME Types
hasImage()imageData()setImageData()image/ *

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.


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.

The above code produces the following output −

PyQt5 library contains QtSql module. It is 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





Borland InterBase Driver



MySQL Driver



Oracle Call Interface Driver



ODBC Driver (includes Microsoft SQL Server)



PostgreSQL Driver



SQLite version 3 or above



SQLite version 2


For this chapter, a connection with a SQLite database is established using the static method −

Other methods of QSqlDatabase class are as follows −

Sr.No.Methods & Description


Sets the name of the database with which connection is sought



Sets the name of the host on which the database is installed



Specifies the user name for connection



Sets the connection object’s password if any



Commits the transactions and returns true if successful



Rolls back the database transaction



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. First step is to create SQlite database using the following statements −

Next, obtain Query object with QSqlQuery() method and call its most important method exec_(), which takes as an argument a string containing SQL statement to be executed.

The following script creates a SQLite database sports.db with a table of sportsperson populated with five records.

To confirm that the SQLite database is created with above records added in sportsmen table in it, use a SQLite Gui utility called SQLiteStudio.

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 QSqlTableModel object is declared in the following manner −

Its editing strategy can be set to any of the following −

QSqlTableModel.OnFieldChangeAll changes will be applied immediately
QSqlTableModel.OnRowChangeChanges will be applied when the user selects a different row
QSqlTableModel.OnManualSubmitAll changes will be cached until either submitAll() or revertAll() is called


In the following example, sportsperson table is used as a model and the strategy is set as −

QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows −

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.

The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user.

The complete code is as follows −

The above code produces the following output −

Try adding and deleting a few records and go back to SQLiteStudio to confirm the transactions.

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


Starts painting on the target device



Draws an arc between the starting and the end angle



Draws an ellipse inside a rectangle



Draws a line with endpoint coordinates specified



Extracts pixmap from the image file and displays it at the specified position



Draws a polygon using an array of coordinates



Draws a rectangle starting at the top-left coordinate with the given width and height



Displays the text at given coordinates



Fills the rectangle with the QColor parameter



Sets a brush style for painting



Sets the color, size and style of pen to be used for drawing


In the following code, various methods of PyQt's drawing methods are used.

The above code produces the following output −


In this chapter, we shall learn Brush Style Constants.

Pyqt Simple Menu App Windows And Mac 10

Brush Style Constants

Given below are the Brush Style Constants −

Qt.NoBrushNo brush pattern
Qt.SolidPatternUniform color
Qt.Dense1PatternExtremely dense brush pattern
Qt.HorPatternHorizontal lines
Qt.VerPatternVertical lines
Qt.CrossPatternCrossing horizontal and vertical lines
Qt.BDiagPatternBackward diagonal lines
Qt.FDiagPatternForward diagonal lines
Qt.DiagCrossPatternCrossing diagonal lines

Predefined QColor Styles

Given below are the Predefined QColor Styles −

Qt.NoBrushNo brush pattern
Qt.SolidPatternUniform color
Qt.Dense1PatternExtremely dense brush pattern
Qt.HorPatternHorizontal lines
Qt.VerPatternVertical lines
Qt.CrossPatternCrossing horizontal and vertical lines
Qt.BDiagPatternBackward diagonal lines
Qt.FDiagPatternForward diagonal lines
Qt.DiagCrossPatternCrossing diagonal lines

Predefined QColor Objects

Given below are the Predefined QColor Objects −


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


Clears clipboard contents



Copies QImage into clipboard



Sets MIME data into clipboard



Copies Pixmap object in clipboard



Copies QString in clipboard



Retrieves text from clipboard

Signal associated with clipboard object is −

Sr.No.Method & Description


Whenever clipboard data changes


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.

The above code produces the following output −

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 −

BMPWindows Bitmap
GIFGraphic Interchange Format (optional)
JPGJoint Photographic Experts Group
JPEGJoint Photographic Experts Group
PNGPortable Network Graphics
PBMPortable Bitmap
PGMPortable Graymap
PPMPortable Pixmap
XBMX11 Bitmap
XPMX11 Pixmap

Following methods are useful in handling QPixmap object −

Sr.No.Methods & Description


Copies pixmap data from a QRect object



Converts QImage object into QPixmap



Creates a pixmap from the given widget



Create pixmap of data in a window



Loads an image file as pixmap



Saves the QPixmap object as a file



Converts a QPixmap to QImage

The most common use of QPixmap is to display image on a label/button.


The following example shows an image displayed on a QLabel by using the setPixmap() method.

The complete code is as follows −

The above code produces the following output −