python logo


Tag: pyqt

pyqt grid layout

PyQt5 supports a grid layout, which is named QGridLayout. Widgets can be added to a grid in both the horizontal and vertical direction. An example of a grid layout with widgets is shown below:

pyqt-grid-layout

Related course:

PyQt5 grid layout example:
The example below creates the grid:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QDialog):

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

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

self.createGridLayout()

windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)

self.show()

def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)

layout.addWidget(QPushButton('1'),0,0)
layout.addWidget(QPushButton('2'),0,1)
layout.addWidget(QPushButton('3'),0,2)
layout.addWidget(QPushButton('4'),1,0)
layout.addWidget(QPushButton('5'),1,1)
layout.addWidget(QPushButton('6'),1,2)
layout.addWidget(QPushButton('7'),2,0)
layout.addWidget(QPushButton('8'),2,1)
layout.addWidget(QPushButton('9'),2,2)

self.horizontalGroupBox.setLayout(layout)

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

Explanation

We import the gridlayout and others with:


from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout

In the method createGridLayout() we create the grid with a title and set the size.


def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)

Widgets are added using


layout.addWidget(Widget,X,Y)

Finally we set the layout.

Several buttons are added to the grid. To add a button click action you need a pyqtslot.

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

Download PyQT5 Examples

Qt4 window

pyqt window PyQt4 window on Ubuntu

In this tutorial you will learn how to create a graphical hello world application with PyQT4.

PyQT4, it is one of Pythons options for graphical user interface (GUI) programming.

Related course:

PyQt4 window example:


This application will create a graphical window that can be minimized, maximimzed and resized it.


#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Show window
w.show()

sys.exit(a.exec_())

The PyQT4 module must be immported, we do that with this line:


from PyQt4.QtGui import *

We create the PyQT4 application object using QApplication():


a = QApplication(sys.argv)

We create the window (QWidget), resize, set the tittle and show it with this code:


w = QWidget()
w.resize(320, 240)
w.setWindowTitle("Hello World!")

Don’t forget to show the window:


# Show window
w.show()

You can download a collection of PyQt4 examples:
 
Download PyQT Code (Bulk Collection)

qt message box

PyQT4 offers message box functionality using several functions.
Messageboxes included in PyQT4 are: question, warning, error, information, criticial and about box.

Related course: Create GUI Apps with Python PyQt5

PyQt4 mesagebox

The code below will display a message box with two buttons:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')

# Show window
w.show()

sys.exit(a.exec_())

Result:

qtMessagebox question qtMessagebox question

There are different types of messageboxes that PyQT4 provides.

PyQT4 Warning Box


You can display a warning box using this line of code:

QMessageBox.warning(w, "Message", "Are you sure you want to continue?")

PyQT4 Information box


We can display an information box using QMessageBox.information()

QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")

Result:

QMessageBox Info QMessageBox Info

PyQT4 Critical Box


If something goes wrong in your application you may want to display an error message.

QMessageBox.critical(w, "Message", "No disk space left on device.")



Result:

QMessagebox QMessagebox

PyQT4 About box


We have shown the question box above.

QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")



Result:

qt Messagebox qt Messagebox

Download PyQT Code (Bulk Collection)

pyqt widgets

QT4 Table

We can show a table using the QTableWidget, part of the PyQt module.  We set the title, row count, column count and add the data.

Related course:

Qt4 Table example


An example below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQt Table

QTableWidget labels


You can set the header using the setHorizontalHeaderLabels() function. The same applies for vertical labels. A qt4 demonstration below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQT Table

Note: These days you can use pyqt5 to create a pyqt table.

QTableWidget click events


We can detect cell clicks using this procedure, first add a function:

# on click function
table.cellClicked.connect(cellClick)

Then define the function:

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

The Python programming language starts counting with 0, so when you press on (1,1) you will see (0,0). Full code to detect table clicks:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# on click function
table.cellClicked.connect(cellClick)

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

If you want to show the cell/row numbers in a non-programmer way use this instead:

def cellClick(row,col):
print "Click on " + str(row+1) + " " + str(col+1)

Tooltip text


We can set tooltip (mouse over) text using the method. If you set tooltips on non-existing columns you will get an error.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# tooltip text
table.horizontalHeaderItem(0).setToolTip("Column 1 ")
table.horizontalHeaderItem(1).setToolTip("Column 2 ")

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table tooltips PyQT Table tooltips

Download PyQT Code (Bulk Collection)

pyqt tabs

open file python

In this short tutorial you will learn how to create a file dialog and load its file contents. The file dialog is needed in many applications that use file access.

Related course:

File Dialog Example
To get a filename (not file data) in PyQT you can use the line:

filename = QFileDialog.getOpenFileName(w, 'Open File', '/')

If you are on Microsoft Windows use

filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\')

An example below (includes loading file data):

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Get filename using QFileDialog
filename = QFileDialog.getOpenFileName(w, 'Open File', '/')
print(filename)

# print file contents
with open(filename, 'r') as f:
print(f.read())

# Show window
w.show()

sys.exit(a.exec_())

Result (output may vary depending on your operating system):

pyqt_file_open PyQt File Open Dialog.

Download PyQT Code (Bulk Collection)

progressbar python