Python

Tag: PyQt

pyqt5 hello world

Make a graphical interface with PyQt?

Graphical interfaces made with PyQt run on: Microsoft Windows, Apple Mac OS X and Linux. We will create a Hello World app with PyQt.

pyqt hello world

Related course:
Create Simple GUI Applications with Python and Qt

Install PyQt

PyQt is available for both Python 2 (2.7.9 tested) and Python 3.

To install write:

pip3 install pyqt5

With apt-get you can use:

python3-pyqt5

PyQt hello world

The app we write will show the message “Hello World” in a graphical window. Import the PyQt5 module.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize

class HelloWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(640, 480))
self.setWindowTitle("Hello world")

centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)

gridLayout = QGridLayout(self)
centralWidget.setLayout(gridLayout)

title = QLabel("Hello World from PyQt", self)
title.setAlignment(QtCore.Qt.AlignCenter)
gridLayout.addWidget(title, 0, 0)

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )

The program starts in the main part.

We initialize Qt and create an object of the type HelloWindow.

We call the show() method to display the window.

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )

The HelloWindow class inherits from the class QMainWindow.

We call its super method to initialize the window.

Several class variables are set: size and window title.

We add widgets to the window, including a label widget (QLabel) which displays the message “Hello World”.

pyqt5 message box

When creating a Python GUI, you may want to show a message box at some point.

Pyqt comes with messagebox support in both PyQt4 and PyQt5. The class to be used is QMessageBox.

In this tutorial you’ll learn how to show a message box on buton click.

qt message box

Related course:
Create Simple GUI Applications with Python and Qt

QMessageBox example

Import QMessageBox from the PyQt5 widgets

from PyQt5.QtWidgets import QMessageBox

A messagebox can easily be added to the window using the code:

QMessageBox.about(self, "Title", "Message")

Complete code:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QSize

class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(300, 200))
self.setWindowTitle("PyQt messagebox example - pythonprogramminglanguage.com")

pybutton = QPushButton('Show messagebox', self)
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,64)
pybutton.move(50, 50)

def clickMethod(self):
QMessageBox.about(self, "Title", "Message")

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

pyqt5 tooltip

A tooltip is a hint in a graphical interface.

Tooltips frequently appear when hovering the mouse over a widget (without clicking). Pyqt supports tool tips, they can be configured for widgets.

pyqt tooltip

Related course:
Create Simple GUI Applications with Python and Qt

Note: Tooltips are not shown on mobile devices because there’s no mouse cursor.

Pyqt5 tooltip

A tooltip can be set using a widgets setTooltip method.

pybutton.setToolTip('This is a tooltip for the QPushButton widget')  

The setToolTip() method sets the tooltip message for a QtWidget.

Copy/paste example:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton
from PyQt5.QtCore import QSize

class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(300, 100))
self.setWindowTitle("PyQt tooltip example - pythonprogramminglanguage.com")

pybutton = QPushButton('Pyqt', self)
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(100,32)
pybutton.move(50, 20)
pybutton.setToolTip('This is a tooltip message.')

def clickMethod(self):
print('PyQt')

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

PyQt line edit

In this tutorial we’ll make an app that displays an input field.

A textbox or LineEdit can be created using the QLineEdit class. Many applications have text inputs like form fields and the like.

QLineEdit

Related course:
Create Simple GUI Applications with Python and Qt

Introduction

Start by importing the QLineEdit widget:

from PyQt5.QtWidgets import QLineEdit

We will also add a text label, to show the user what to type.
Import QLabel:

from PyQt5.QtWidgets import QLabel

Then add both to the screen:

self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)

self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)

The text value can be printed using:

print('Your name: ' + self.line.text())

QLineEdit Example

We start with the code followed by the explanation.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize

class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(320, 140))
self.setWindowTitle("PyQt Line Edit example (textfield) - pythonprogramminglanguage.com")

self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)

self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)

pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,32)
pybutton.move(80, 60)

def clickMethod(self):
print('Your name: ' + self.line.text())

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )

 

pyqt5 sliders

PyQt5 comes with sliders out of the box.

Sliders can be either vertical or horizontal. We can connect them with a method the same way as we do with buttons.

A slider is often used in conjunction with a spinbox, QSpinBox. In this example we won’t use a spinbox, as that’s optional. You can connect a slider to any widget or functionality you want.

Related course:
Create Simple GUI Applications with Python and Qt

Slider example
We create a groupbox which contains 4 sliders. A slider is created with the class QSlider, which accepts the flags Qt.Horizontal or Qt.Vertical.

pyqt sliders

If you want to add a slider to your existing code, don’t forget to import QSlider from PyQt5.QtWidgets.

# pythonprogramminglanguage.com
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox,
QMenu, QPushButton, QRadioButton, QVBoxLayout, QWidget, QSlider)

class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)

grid = QGridLayout()
grid.addWidget(self.createExampleGroup(), 0, 0)
grid.addWidget(self.createExampleGroup(), 1, 0)
grid.addWidget(self.createExampleGroup(), 0, 1)
grid.addWidget(self.createExampleGroup(), 1, 1)
self.setLayout(grid)

self.setWindowTitle("PyQt5 Sliders")
self.resize(400, 300)

def createExampleGroup(self):
groupBox = QGroupBox("Slider Example")

radio1 = QRadioButton("&Radio horizontal slider")

slider = QSlider(Qt.Horizontal)
slider.setFocusPolicy(Qt.StrongFocus)
slider.setTickPosition(QSlider.TicksBothSides)
slider.setTickInterval(10)
slider.setSingleStep(1)

radio1.setChecked(True)

vbox = QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(slider)
vbox.addStretch(1)
groupBox.setLayout(vbox)

return groupBox

if __name__ == '__main__':
app = QApplication(sys.argv)
clock = Window()
clock.show()
sys.exit(app.exec_())

 

pyqt textarea

QPlainTextEdit is a multiline text area in PyQt. To set the text, we use its method insertPlainText(). We can set its position and size using the methods move() and resize().

pyqt text area

Related course:
Create Simple GUI Applications with Python and Qt

Textarea

The example below creates a text area using PyQt5.

We will create the usual QMainWindow to add the widget to. It is just for plain text, like notepad. To add new lines we add the \n character.

# PyQt5 text area
# pythonprogramminglanguage.com

import sys
from PyQt5.Qt import QApplication, QClipboard
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPlainTextEdit
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(440, 240))
self.setWindowTitle("PyQt5 Textarea example")

# Add text field
self.b = QPlainTextEdit(self)
self.b.insertPlainText("You can write text here.\n")
self.b.move(10,10)
self.b.resize(400,200)

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )

pyqt checkbox

A checkbox can be created using the QCheckBox widget. When creating an new checkbox with the QCheckBox class, the first parameter is the label.

To apply actions to the toggle switch, we call .stateChanged.connect() followed by a callback method. When this method is called, it sends a boolean as state parameter. If checked, its the value QtCore.Qt.checked.

checkbox pyqt

Related course:
Create Simple GUI Applications with Python and Qt

Checkbox example

The example below creates a checkbox which calls the method clickBox when toggled.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(140, 40))
self.setWindowTitle("Checkbox")

self.b = QCheckBox("Awesome?",self)
self.b.stateChanged.connect(self.clickBox)
self.b.move(20,20)
self.b.resize(320,40)

def clickBox(self, state):

if state == QtCore.Qt.Checked:
print('Checked')
else:
print('Unchecked')

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )

pyqt combobox

A combobox can be created with the QComboBox class. Items are added using the class method addItem, followed by a string parameter.

Sometimes its called a listbox, as it shows a list of items a user can select from. If you want a user to choose from a set of items, the listbox is the best option.

pyqt combobox

Related course:
Create Simple GUI Applications with Python and Qt

Combobox example

The code below creates a combobox using the class QComboBox.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QComboBox
from PyQt5.QtCore import QSize, QRect

class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(640, 140))
self.setWindowTitle("Combobox example")

centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)

# Create combobox and add items.
self.comboBox = QComboBox(centralWidget)
self.comboBox.setGeometry(QRect(40, 40, 491, 31))
self.comboBox.setObjectName(("comboBox"))
self.comboBox.addItem("PyQt")
self.comboBox.addItem("Qt")
self.comboBox.addItem("Python")
self.comboBox.addItem("Example")

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )