logo


Tag: pyqt5

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


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 dialog

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())

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(self)

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 colors

Colors in PyQt5 are defined using the method QColor(r, g, b). All colors on the screen are a combination of the red, green and blue values. Every color value should be in the range 0..255.
In a QPainter widget you can pass a color to the setBrush method.

QColor QColor example

Related course:
Create GUI Apps with PyQt5

PyQt5 color example:
This example draws a variety of colors in a QPainter widget using the setBrush and QColor methods.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt rectangle colors - pythonspot.com'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.initUI()

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

# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)

# Add paint widget and paint
self.m = PaintWidget(self)
self.m.move(0,0)
self.m.resize(self.width,self.height)

self.show()

class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)

qp.setPen(Qt.black)
size = self.size()

# Colored rectangles
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(0, 0, 100, 100)

qp.setBrush(QColor(0, 200, 0))
qp.drawRect(100, 0, 100, 100)

qp.setBrush(QColor(0, 0, 200))
qp.drawRect(200, 0, 100, 100)

# Color Effect
for i in range(0,100):
qp.setBrush(QColor(i*10, 0, 0))
qp.drawRect(10*i, 100, 10, 32)

qp.setBrush(QColor(i*10, i*10, 0))
qp.drawRect(10*i, 100+32, 10, 32)

qp.setBrush(QColor(i*2, i*10, i*1))
qp.drawRect(10*i, 100+64, 10, 32)

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

Download PyQT5 Examples

PyQt5 Matplotlib

Matplotlib plots can be included in a PyQt5 application.
Several imports need to be added:


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

We create a widget called PlotCanvas that includes the Matplotlib plot.

pyqt5-matplotlib Matplot plot in PyQt5 window

PyQt5 Matplotlib example
The example below embeds a matplotlib plot in a PyQt5 window.


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 matplotlib example - 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('PyQt5 button', self)
button.setToolTip('This s an example 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 Matplotlib Example')
self.draw()

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

Download PyQT5 Examples

PyQt5 Treeview

PyQt5 (python with qt5 bindings) supports a tree view widget (class QTreeView). In this article we will show how to use the widget.

treeview pyqt5

The image shows a QTreeView widget with data inside it.

Related course:
Create GUI Apps with PyQt5

PyQt5 Treeview Example


The code below will create a treeview using the QTreeView class (Run using Python 3). Data is added to the treeview by code. Explanation of the code is below the code block.


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtGui import QIcon

from PyQt5.QtCore import (QDate, QDateTime, QRegExp, QSortFilterProxyModel, Qt,
QTime)
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QGridLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTreeView, QVBoxLayout,
QWidget)

class App(QWidget):

FROM, SUBJECT, DATE = range(3)

def __init__(self):
super().__init__()
self.title = 'PyQt5 Treeview Example - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 240
self.initUI()

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

self.dataGroupBox = QGroupBox("Inbox")
self.dataView = QTreeView()
self.dataView.setRootIsDecorated(False)
self.dataView.setAlternatingRowColors(True)

dataLayout = QHBoxLayout()
dataLayout.addWidget(self.dataView)
self.dataGroupBox.setLayout(dataLayout)

model = self.createMailModel(self)
self.dataView.setModel(model)
self.addMail(model, '[email protected]', 'Your Github Donation','03/25/2017 02:05 PM')
self.addMail(model, '[email protected]', 'Github Projects','02/02/2017 03:05 PM')
self.addMail(model, '[email protected]', 'Your Phone Bill','01/01/2017 04:05 PM')

mainLayout = QVBoxLayout()
mainLayout.addWidget(self.dataGroupBox)
self.setLayout(mainLayout)

self.show()

def createMailModel(self,parent):
model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")
return model

def addMail(self,model, mailFrom, subject, date):
model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

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.

Treeview Explanation


We create a new tree view object using the line:


self.dataView = QTreeView()

The view is set to have a model,


self.dataView.setModel(model)

Where model is


model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")

Then we add data using:


model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

Download PyQT5 Examples

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


123