python logo


Tag: pyqt5

pyqt statusbar

PyQt5 supports a window status bar. This is a small bar at the bottom of a window that sometimes appears, it can contain text messages. To add a status bar add the line:


self.statusBar().showMessage('Message in statusbar.')

A statusbar can be added to the main window (QMainWindow). It is one of the methods the class itself contains;

Related course:
Create GUI Apps with PyQt5

PyQt5 statusbar example:
The program below adds a statusbar to a PyQt5 window:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5.QtGui import QIcon

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 status bar example - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.statusBar().showMessage('Message in statusbar.')
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

The example creates a window (QMainWindow). We set the screen parameters using:


self.left = 10
self.top = 10
self.width = 640
self.height = 480

Window properties are set in the initUI() method which is called in the constructor. The method:


statusBar().showMessage()

sets the text on the statusbar.

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

qwidget set position

pyqt tabs

pyqt5 layout

pyqt5 qpainter

pyqt color picker

PyQt5 supports a color picker known as QColorDialog. This dialog is a typical dialog that you would see in a paint or graphics program.

To get a color from PyQt5 dialog simply call:


color = QColorDialog.getColor()

QColorDialog A color dialog using PyQt5

Related course:

PyQt5 color dialog example
The example below opens a QColorDialog after clicking the button (qpushbutton), and returns the selected color.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QColorDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QColor

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 color dialog - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('Open color dialog', self)
button.setToolTip('Opens color dialog')
button.move(10,10)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
openColorDialog()

def openColorDialog(self):
color = QColorDialog.getColor()

if color.isValid():
print(color.name())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

qcolor pyqt5

pyqt drag and drop

Like any modern GUI toolkit, PyQt supports drag and drop. A widget parameter must be set using the setDragEnabled(True) method call. A custom widget should then be set to accept a drop with setAcceptDrops(True).

pyqt-drag-and-drop Drag and drop using PyQt5

Related course:
Create GUI Apps with PyQt5

PyQt5 drag and drop example


Drag text from the input field to the label, the label will update its text. Use pyqtslot to connect the action to a function.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 drag and drop - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 60
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

editBox = QLineEdit('Drag this', self)
editBox.setDragEnabled(True)
editBox.move(10, 10)
editBox.resize(100,32)

button = CustomLabel('Drop here.', self)
button.move(130,15)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

class CustomLabel(QLabel):

def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)

def dragEnterEvent(self, e):
if e.mimeData().hasFormat('text/plain'):
e.accept()
else:
e.ignore()

def dropEvent(self, e):
self.setText(e.mimeData().text())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

The textbox is created with the call QLineEdit(). A custom class (CustomLabel) is created that accepts drag and drop. Both events are defined as methods and have their logic executed if the event occurs.

Download PyQT5 Examples

pyqt5 font

PyQt5 comes with a font dialog that you may have seen in a text editor. This is the typical dialog where you can select font, font size, font style and so on. Of course the look and feel depends on the operating system.

To open this dialog import QFontDialog call:

QFontDialog.getFont()

To use it, import QFontDialog from QtWidgets like this:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog

Related course:

PyQt5 font dialog

The example below opens a font dialog on a button event, the selected font (font family including size) will be returned as a string.

pyqt-font-dialog Font Dialog using PyQt5

Opening a font dialog is as simple as

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

Then add a pyqt5 button that opens the dialog. To do that, you need a pyqtslot.

A full code example is shown below


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 font dialog - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('Open PyQt5 Font Dialog', self)
button.setToolTip('font dialog')
button.move(50,50)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
openFontDialog()

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

pyqt5 matplotlib

Matplotlib offers powerful visualizations that can be seamlessly integrated into a PyQt5 application. For this, specific libraries and imports are required.

Here’s how you can include Matplotlib plots within a PyQt5 application:

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

The primary component here is a widget named ‘PlotCanvas’ which houses the Matplotlib visualization.

Matplot plot in a PyQt5 window

Integration of Matplotlib with PyQt5
The example provided below illustrates the embedding process of a Matplotlib plot within a PyQt5 window. Additionally, we’ll integrate a qpushbutton for demonstration.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.left = 10
self.top = 10
self.title = 'PyQt5 and Matplotlib Integration - pythonspot.com'
self.width = 640
self.height = 400
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
m = PlotCanvas(self, width=5, height=4)
m.move(0,0)
button = QPushButton('Sample PyQt5 Button', self)
button.setToolTip('This is an illustrative button')
button.move(500,0)
button.resize(140,100)
self.show()

class PlotCanvas(FigureCanvas):

def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()

def plot(self):
data = [random.random() for i in range(25)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('PyQt and Matplotlib Demonstration')
self.draw()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

For those keen on diving deeper into PyQt5’s capabilities, consider downloading these comprehensive PyQT5 Example Codes.

Navigation:

pyqt5 browser

QWebView Class Simplified QWebView class simplified

PyQt5 supports a widget that displays websites named QWebView.

QWebView uses the Webkit rendering engine
The web browser engine is used by Safari, App Store and many OS X applications.

The load() method opens the url (QUrl) in the argument. You can create a QUrl using: QUrl(url).

The show() method is required to display the widget.

Related course:

Installation


To use this widget you may need to install an additional package:


sudo apt-get install python3-pyqt5.qtwebkit

Read more about PyQt5.

PyQt5 webkit example


The example below loads a webpage in a PyQt5 window.


#!/usr/bin/env python

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebKit import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow

app = QApplication(sys.argv)

web = QWebView()
web.load(QUrl("https://pythonspot.com"))
web.show()

sys.exit(app.exec_())

pyqt5-webkit Webkit in PyQt5

Download PyQT5 Examples

pyqt5 webview

QWebview inside a browser PyQt5 Webkit (QWebview) inside a browser

PyQt5 comes with a webkit webbrowser. Webkit is an open source web browser rendering engine that is used by Apple Safari and others. It was used in the older versions of Google Chrome, they have switched to the Blink rendering engine.

Related course:
Create GUI Apps with PyQt5

QWebView
The widget is called QWebView and webpages (HTML content) can be shown through this widget, local or live from the internet.

Methods
The QWebView class comes with a lot of methods including:


  • back (self)

  • forward (self)

  • load (self, QUrl url)

  • reload (self)


#!/usr/bin/python

import PyQt5
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtNetwork import *
import sys
from optparse import OptionParser

class MyBrowser(QWebPage):
''' Settings for the browser.'''

def userAgentForUrl(self, url):
''' Returns a User Agent that will be seen by the website. '''
return "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

class Browser(QWebView):
def __init__(self):
# QWebView
self.view = QWebView.__init__(self)
#self.view.setPage(MyBrowser())
self.setWindowTitle('Loading...')
self.titleChanged.connect(self.adjustTitle)
#super(Browser).connect(self.ui.webView,QtCore.SIGNAL("titleChanged (const QString&)"), self.adjustTitle)

def load(self,url):
self.setUrl(QUrl(url))

def adjustTitle(self):
self.setWindowTitle(self.title())

def disableJS(self):
settings = QWebSettings.globalSettings()
settings.setAttribute(QWebSettings.JavascriptEnabled, False)

app = QApplication(sys.argv)
view = Browser()
view.showMaximized()
view.load("https://pythonspot.com")
app.exec_()

Related course:
Create GUI Apps with PyQt5

pyqt treeview