Python Graphical User Interface
Mastering data display in PyQt5 requires a deep understanding of views like List View, Tree View, Table View and Column View. These powerful components allow you to present complex data in clean, organized and easily navigable formats. The List View is perfect for showcasing items in a simple, linear fashion while the Tree View excels at displaying hierarchical data, making it easy for users to explore relationships between elements. Table View takes it a step further, providing a grid based layout for managing vast amounts of structured data with ease. Finally, the Column View offers a sleek, multi-column interface that’s ideal for browsing large datasets in a clear, segmented manner. With these views you can transform raw data into interactive, user-friendly displays that captivate and engage users, making your applications both functional and visually impressive.
Table of Content
- Introduction
- List view
- Tree view
- Table view
- Column view
Introduction
After discussing button widgets, we shall now move on to our
next topic, which is about Item Views in Qt Designer. There
has to be some approach for accessing, managing and
displaying the data to the user. So, based on the software
design pattern of Model-View-Controller, PyQt5
utilizes the same architecture of Model View. The data from
the data source will be accessed by the model and will
provide data to the view. This view will present the items
stored in a model and reflect the changes to the data in the
model. The data editing in the model will be handled by the
delegate, who will also be responsible for items drawn in the
view. You may visit the website at https://doc.qt.io where
a plethora of information on PyQt5 functions and properties
is provided.
Our main focus in this section will be on learning about
QListView, QTreeView, QTableView and QColumnView. We will be
focusing on properties and some useful methods. All these
widgets are available under Item Views in Qt Designer as
shown in the figure. The user can select any of the widgets under Item Views and drag and drop in a GUI form.
The base class for these widgets is an abstract class QAbstractItemView which provides support for header
management and item selection. We have already seen
QObject and QWidget classes when dealing with Button type
widgets. The same applies to Item Views widgets, too. There
are other classes we will be discussing about, such as QFrame,
QAbstractScrollArea and QAbstractItemView class, which will be
discussed at the end of this section. Moreover, we will also
discuss QStandardItemModel at the end which provides a
standard item based approach for working with the model.
Data Presentation
Item View widgets can be used to present data in a graphical
and user friendly manner. Users can use these widgets to
display data in simple list formats (QListView), hierarchical
tree structures (QTreeView) or rows and columns (QTableView).
Data editing and manipulation are capabilities that are
already built into Item View widgets. The user can add,
remove or alter objects to interact with the data shown in
the widgets and can also design behaviors and set properties
for these activities using Qt Designer. Since the user can
alter their appearance and behavior and may also design
unique user interfaces suited to their requirements, item
views are entirely adjustable. The Model-View architecture, a
key Qt idea for separating data representation model from
the visual display view and user interaction (delegate) is
also introduced to the user. The user may better understand
the ideas of models, views and delegates as well as how
they interact by learning about item view widgets. The
important properties of QFrame, QAbstractScrollArea and
QAbstractItemView are covered with images at the end as add-on information.
List View
It is one of the Model/View frameworks of PyQt5. In the
QListView class, we can store the items as an icon collection or
as a non-hierarchical list. There will be a display of items in a
listview using either ListMode or IconMode, and the current view
mode is determined using viewMode(). In a QListView, widget
items can be spaced/laid or can be rendered as small or
large icons.
Important Properties
Let us check some important properties.
Movement
This property describes the movement of items in a QListView
widget. There are three options.
- If the user selects Static, there will be no movement of
items. - If the user selects Free, there will be drag and drop of
items to any position in the QListView widget. - If the user selects Snap, there will be a drag and drop of
items to the notional grid positions denoted by the
gridSize parameter.
Designer
Flow
Using this property, we can set the direction for the layout of
the items. By default, the items are laid out in the QListView widget from top to bottom. Items can also be laid out from
left to right.
Is wrapping
We can set the items layout wrapping when checked, using
this property. Default value is False.
Designer
resizeMode
Using this property, we can decide the layout of the items
again by resizing of QListView widget. By default, the value is
Fixed, that is, on resizing of QListView widget, the items will
not be laid out, whereas they will be laid out again when set
to Adjust.
Designer
LayoutMode
Using this property, we can determine if the items’ layout
should be delayed or happen immediately. So, the items’
layout happens all at once when set to SinglePass or in batches of batchSize items when set to Batched.
Designer
Spacing
Whenever there is a requirement to pad an empty space size
around an item, we can use this property. By default, its
value is set to 0.
Designer
Grid Size
We can set the grid size using this property, by setting the
width and height in which items are laid out. The default
value of width and height is 0 indicating no grid.
Designer
viewMode
The view mode of QListView widget is set using this property.
When set to ListMode, drag and drop is disabled, as the
default movement will be Static. When set to IconMode, drag and drop is enabled, as the default movement will be Free.
Designer
Model Column
This property will set the visibility of the column in the
model. The default value is 0, indicating the display of the
first column in the model.
Designer
UniformItemSizes
When set to True, all the items in the QListView widget will
have the same size. The default value is False.
in Qt Designer
Batchsize
When the layoutMode value is set to batch, in each batch, we
can set the number of items. The default value is set to 100.
Designer
wordWrap
The item text is wrapped at word breaks as needed if this
parameter is set to True.
Designer
Selectionrectvisible
The selection rectangle is visible when set to True or else it
will be invisible. The default value is False.
widget in Qt Designer
- setModel(model): We can set the view model when this
method is called. - setItemDelegate(delegate): We can set an item delegate for
the model/view framework of the view.
setIconSize(size): The icon size can be set using this
method. - setDragEnabled(bool): When the bool value is set as True,
we can drag the items around in the view. - setAcceptDrops(bool): When the bool value is set as True,
we can drop the items into the view. - setAlternatingRowColors(bool): The view background will be
drawn with alternating colors when the bool value is
True. - setCurrentIndex(index): Using this method, the item at the
index specified will be set as the current item. - update(index): The area at the specified index will be
updated. - clearSelection(): Here, all the selected items will be
deselected. - selectAll(): All the items in the view will be selected.
Important Signal of QAbstractItemView Base
Class
- pressed(index): An item at the index is pressed using the
mouse button. - entered(index): The item at the index is entered by the
mouse cursor. Mouse tracking is turned on for use. - activated(index): The user activates the item at the index.
- clicked(index): An item in the view is clicked with the left
mouse button as specified by the index. - doubleClicked(index): An item in the view is double-clicked
by the mouse button as specified by the index.
Now, we shall see an example of a ListView widget.
Consider the following code of run_listView_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from PyQt5.QtGui import QStandardItemModel
from listView_eg1 import *
class MyListView(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.myfruits = ['apple', 'orange',
'banana', 'pear'] # creating a list object
# creating an object of one of the
model/view class for storing custom data.
model = QStandardItemModel()
# A view is set up to display the items in
the listView object
self.ui.mylV1.setModel(model)
# iterating each elements of the myfruits
list object
for i in self.myfruits:
# QStandardItem provides the items in a
QStandardItemModel
item = QtGui.QStandardItem(i)
# adding items to the model using
appendRow
model.appendRow(item)
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyListView()
w.show()
sys.exit(app.exec_())
Output:
From the above code, we can view that we are displaying
fruit items row-wise on a listView widget.
Tree View
One of the parts of Qt’s Model View framework creates a tree
representation of items from the model. In order to display
data provided by models descended from the
QAbstractItemModel class, QTreeView implements the interfaces
described by the QAbstractItemView class. The model/view
architecture ensures that as the model changes, the tree
view’s contents are updated. A tree view’s default
model/view implementation is offered by the QTreeView class.
Important Properties
Let us now check some important properties.
Autoexpanddelay
During a drag and drop operation, the delay time is specified
in milliseconds before items in a QTreeView widget are opened
using this property. The default value is -1 indicating the
disabling of the auto expansion property.
in Qt Designer
Indentation
We can set the indentation of the items for each level of the
QTreeView widget, measured in pixels. The horizontal distance
from the viewport edge to the items in the first column
specifies the indentation for top-level items. The indentation
is specified from their parent items for child items.
Designer
rootisdecorated
We can determine whether controls for expanding and
collapsing top level items are to be displayed or not. The
controls will not be displayed for top level items if unchecked
and make a single level tree structure appear like a simple
list of items. The default is checked.
Qt Designer
Uniformrowheight
When checked, all the items in the QTreeView widget will have
the same height. The first item in the view provides the
height. When data changes on that item, it is updated
automatically. By default, it is unchecked.
widget in Qt Designer
ItemsExpandable
The default value is checked and this property will decide
whether the user can interactively expand and collapse
items.
in Qt Designer
Sortingenabled
The default value is unchecked. If set to True, then sorting
will be enabled for the QTreeView widget, else it will be
disabled.
Qt Designer
Animated
The Tree view will animate the expansion and collapsing of
branches when set to True. When unchecked, there will be immediate expansion and collapsing of branches without a
display of animation.
Designer
Allcolumnshowfocus
The default value is unchecked, meaning only one column
will show focus. When checked, all columns will show focus.
widget in Qt Designer
wordWrap
The item text is wrapped when necessary, at word breaks, if
this attribute is True. It is unchecked by default, that is, set
as False.
Designer
Headerhidden
The header is hidden when checked, or else it is displayed
when unchecked. The default value is set as False.
Qt Designer
Expandsondoubleclick
The default value is set to True, and from the name, we can
understand that the items can be expanded or collapsed by
double-clicking.
widget in Qt Designer
Now, we shall see an example of the tree view widget.
Consider the following code of run_TreeView_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel
from TreeView_eg1 import *
class MyTreeView(QMainWindow):
# setting object Name, Contact_Number, City,
Profession
# with values as 0 1 2
3
Name, Contact_Number, City, Profession =
range(4)
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# set to False means making a single level
tree structure appear like a simple list of items
self.ui.treeView.setRootIsDecorated(False)
# set to Truemeans To draw the item's
background, Base and AlternateBase will be used.
# observe the output with background color
to be changed on alternate rows
self.ui.treeView.setAlternatingRowColors(True)
# calling myTreeViewModelCreation method
mymodel =
self.myTreeViewModelCreation(self)
# model is set for the Treeview
self.ui.treeView.setModel(mymodel)
# filling Data on passing Name,
Contact_Number, City and Profession headers
# by calling myaddition method
self.myaddition(mymodel, 'Divya',
'9857611111','Delhi','Scientist')
self.myaddition(mymodel, 'Sargam',
'9857622222','Kolkata','HouseWife')
self.myaddition(mymodel, 'Sugandh',
'9857633333','Aligarh','Engineer')
self.myaddition(mymodel, 'Munnu',
'9857644444','Mumbai','Cricketer')
self.show()
def myTreeViewModelCreation(self, myparent):
# creating a new item model with the
initial rows = 0, initial columns = 4 and specified
parent
mymodel = QStandardItemModel(0, 4,
myparent)
#setHeaderData(): Sets the data in the
header for the provided section(0, 1, 2 and 3)
#with the specified orientation as
Horizontal to the
# given value (Name, Contact_Number, City
and Profession).
# if the header's data is updated , it will
be returning True
mymodel.setHeaderData(0, Qt.Horizontal,
"Name")
mymodel.setHeaderData(1, Qt.Horizontal,
"Contact_Number")
mymodel.setHeaderData(2, Qt.Horizontal,
"City")
mymodel.setHeaderData(3, Qt.Horizontal,
"Profession")
# returning the item model
return mymodel
def myaddition(self,mymodel, myname,
mycontactnumber, mycity, myprofession):
# insertRow for displaying the data
mymodel.insertRow(0)
# index(): gives the QModelIndex associated
with the item
# setData(): set the specified value (which
are passed as arguments)
# to the item's data for the given role.
# ----> Also, setData() is in charge of
changing the details
# information of a role related to a
QModelIndex.
mymodel.setData(mymodel.index(0,
self.Name), myname)
mymodel.setData(mymodel.index(0,
self.Contact_Number), mycontactnumber)
mymodel.setData(mymodel.index(0,
self.City), mycity)
mymodel.setData(mymodel.index(0,
self.Profession), myprofession)
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyTreeView()
w.show()
sys.exit(app.exec_())
Output:
From the above code, we see that we are adding the data to
the Treeview object using code.
Table View
A table view is implemented to display items from a model
using QTableView. It is one of the Model/View frameworks of
PyQt5. To show data provided by models derived from the QAbstractItemModel class, QTableView implements the interfaces defined by the QAbstractItemView class. The QTableView widget
from PyQt5 will be used to build spreadsheets and tables.
The rows and columns will be creating the Tables. Cells are
formed where rows and columns intersect. The TableView
widget allows editing and interaction with each cell. The
table view receives instructions on how to populate and
format the table cells from the rowCount(), columnCount() and
data() methods for the item model.
Important Properties
Let us now check some important properties.
showgrid
This property will decide whether the grid is to be displayed
or not. The grid will be drawn when checked, or else there
will be no grid. The default value is set to True.
Designer
Gridstyle
The pen style is set for drawing the grid using the gridStyle
property.
Designer
Sortinenabled
The default value is unchecked, which means sorting is
disabled for the QTableView widget. When checked, the sorting
will be enabled.
Qt Designer
wordWrap
The default value is True indicating that the item text will be
wrapped at necessary word breaks and otherwise not.
Designer
Cornerbuttonenabled
The default value is True, indicating that the top-left corner
button will be enabled. When clicked, all the cells in the
QTableView widget will be selected.
widget in Qt Designer
Now, we shall see an example of Table View widget.
Consider the following code of run_TableView_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from PyQt5.QtCore import Qt, QAbstractTableModel#
using QAbstractTableModel
from PyQt5.QtGui import QStandardItemModel
from TableView_eg1 import *
class MyTableView(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#creating a 2-D list
mydata = [
[11, 12, 13, 14],
[15, 16, 17, 18],
[19, 20, 21, 22],
[23, 24, 25, 26]
]
self.model = MyTableModel(mydata) # calling
a custom model MyTableModel and passing mydata as
a parameter into the constructor
# model is set for the Tableview
self.ui.tableView.setModel(self.model)
# creating a custom model for interfacing between
data object and view
class MyTableModel(QAbstractTableModel):
def __init__(self, mydata):
super().__init__()
self._data = mydata
# data is returned for given table locations
and parameters index and role are passed
def data(self, index, role):
if role == Qt.DisplayRole: # for returning
string
# The table location for which the
information is currently being requested
# is given by the index parameter
# The row and column numbers in the
view are provided by the
# functions .row() ---> (indexing into
the outer list)
# and.column(indexing into the sub-
list) ---> (), respectively.
# in the form of nested list , data is
stored
return self._data[index.row()]
[index.column()]
# number of rows is returned
def rowCount(self, index):
# outer list length is returned.
return len(self._data)
# number of columns is returned
def columnCount(self, index):
# first sub list is taken .that is no. of
elements in inner list and the length is being
returned
# if all rows are of an equal length , then
only it will work
return len(self._data[0])
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyTableView()
w.show()
sys.exit(app.exec_())
Output:
In the above code, we can see the display of values using a
simple data structure by using a custom class MyTableModel.
Column View
One of the parts of Qt’s Model/View framework illustrates a
model in many QListViews, one for each tree hierarchy.
Moreover, it is coined as list cascading. In order to display
data provided by models derived from the QAbstractItemModel
class, QColumnView implements the interfaces described by the
QAbstractItemView class.
Important Properties
Let us now check some important properties.
Resizegripsvisible
This property will decide whether resize grips are
experienced by list views or not. The default value is set to
True.
widget in Qt Designer
Now, we shall see an example of a ColumnView widget.
Consider the following code of run_ColumnView_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication, QFileSystemModel# importing
QFileSystemModel
from ColumnView_eg1 import *
from PyQt5.QtCore import QDir
class MyColumnView(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# creating an object of QFileSystemModel()
class
self.myfile = QFileSystemModel()
# serTootPath(): Installs a file system
watcher on it and changes the directory
# that the model is watching to newPath.
The model will update if files
# or directories in this directory change.
self.myfile.setRootPath(QDir.rootPath())
print(QDir.rootPath()) # returns the root
directory's absolute path.
print(QDir.homePath()) # returns the user's
home directory's absolute path.
print(QDir.currentPath()) # provides the
current directory of the application's absolute
path.
for dirname in (QDir.rootPath(),
QDir.homePath(), QDir.currentPath()):
# model is set for the Columnview
self.ui.columnView.setModel(self.myfile)
# setRootIndex: Sets the item at the
specified index as the root item.
self.ui.columnView.setRootIndex(self.myfile.index(d
irname))
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyColumnView()
w.show()
sys.exit(app.exec_())
Output:
In the above code, the views have a rootIndex that instructs
them which portion of the model to display and the
QFileSystemModel has a rootPath that specifies the root from
which the files will be monitored.
Qframe
The widgets base class, which can have a frame, is provided
by QFrame class. A frame shape and a shadow style that will be
used to distinguish the frame from neighboring widgets,
visually, make up the frame style. We shall now delve into
their important properties.
Frameshape
This property will set the available frameShape value to the
user from the frame style. Users may choose any of the
frame shapes from the available list. The default value is
StyledPanel in Qt Designer and then drag and drop any
ItemView widget in a GUI form. Different frame shapes value
available to the user are as follows.
user
Frameshadow
In order to give a 3D effect to frames, the shadow type can
be set using this property. User may choose any of the
following from the availability which is Plain, Raised or
Sunken.
Linewidth
Using this property, we can set the lineWidth of the frame
border. The default value is 1.
Midlinewidth
Using this property, we can determine how wide that extra
line must be in the middle of the frame. To create a
distinctive 3D effect, a third color is used. The default value
is 0.
You may go through various combinations of line width and
frame styles from https://doc.qt.io.
QAbstractscrollarea
In QAbstractScrollArea class common for all the model based
item views widgets of Qt Designer, there is a viewport area
contents providing a central widget that is scrolled. There is
a vertical and horizontal scroll bar next to the viewport. The
viewport expands when a scrollbar is hidden to cover the
available space and shrinks when it is visible again to make
its room.
VerticalScrollbarpolicy
Using this property, we can set the policy for the vertical
scrollbar. The default value is ScrollBarAsNeeded. Users may
choose either of the other options ScrollBarAlwaysOff and
ScrollBarAlwaysOn.
Sizeadjustpolicy
Using this property, we can set the policy on how the scroll
area size changes when the view port size is changed. The
default value is AdjustIgnored.
Qabstractitemview
The QAbstractItemView class common for all the model based
item views widgets of Qt Designer gives item view class’s
fundamental capabilities.
Auto scroll
This property is set to True by default and the
QAbstractItemView widget will automatically scroll its contents if
the user moves it within 16 pixels of the viewport edge.
Autoscrollmargin
The area size will be set using this property when auto scrolling is enabled. The default value is 16 pixels.
Edit trigger
When checked, actions of QAbstractItemView widget will initiate
item editing. Doubleclicked and EditKeyPressed are checked by
default and are combined using the OR operator.
Tablet navigation
When set, item navigation with tab and back tab is enabled.
Showdropindicator
When set, the drop indicator is visible in QAbstractItemView
widget while dragging and dropping objects.
Dragenabled
When set, the QAbstractItemView widget supports dragging of
its own items.
Dragdropoverwritemode
Using this property, we can set the drag-and-drop behavior
of the QAbstractItemView widget. When set to True, dropping
the selected data will replace the item’s existing data,
whereas on moving, the data will clear the item. When the
data is dropped and set to False, the selected data will be
added as a new item. The item is also removed when the
data is moved. It is unchecked by default.
Dragdropmode
This property explains various drag and drop actions that the
QAbstractItemView widget can take.
Default drop action
Using this property, we can set the default drop action used
in the QAbstractItemView widget. When the supported actions
support CopyAction and the property is not set the drop action
is CopyAction.
Alternatingrowcolor
When set to True, using Base and AlternateBasecolor, the item
background will be drawn. If set to False using Base color,
which is the default value, only the item background will be
drawn.
Selection mode
Using this property, the user can decide whether to select
one item or many items and in many item selections,
whether the continuous range of items must be selected or not.
Selection behavior
QAbstractItemView widget will set the selection behavior using
this property.
Icon size
Using this property, the item size icons will be set.
Textelidemode
This property will set the position of QAbstractItemView widget
in elided text whose default value is ElideRight.
Verticalscrollmode
This property will set the scrolling of QAbstractItemView widget
item contents in the vertical direction. Scrolling can be
performed either per item or per pixel.
Horizontalscrollmode
This property will set the scrolling of QAbstractItemView widget
item contents in the horizontal direction. Scrolling can be
performed either per item or per pixel.
Qstandarditemmodel
It is a Model/View Class and a component of the Model/View
Framework in PyQt5. QStandardItem provides the items in a
QStandardItemModel. Data is provided by this model in any view
which supports the interface such as QListView, QTableView and
QTreeView.
Typically, we start with an empty QStandardItemModel and use
appendRow() method to add items to the model and item()
method to access individual items when you want a list or
tree. To arrange items into a table that your model
represents, we normally supply the table’s dimensions to the
QStandardItemModel constructor and execute setItem(). With the
help of setHorizontalHeaderLabels() and setVerticalHeaderLabels(),
we may set the header labels of our model.
The model can be searched for items using findItems() and
sorted using sort() methods.
To remove all elements from the model, we can use the
clear() method.
Please refer to the link https://doc.qt.io for more
information. Examples are already demonstrated while
explaining different views.
Conclusion
In this section, we learned about in-depth understanding of
Item view widgets, including QTableView, QTreeView and QListView
which have proven to be effective tools for presenting data
in an ordered and structured way. List formats, hierarchical
tree structures and tabular representations are just a few of
the alternatives they provided for data presentation. These
widgets are efficient in presenting data in a graphical and
user-friendly manner. Additionally, data editing and
modification features are included in item view widgets.
Users can quickly add, remove or change items to interact with the data displayed. The user interface is made more
interactive by allowing users to specify behaviors and
change parameters for these actions using Qt Designer.
Additionally, the Model-View architecture, a crucial Qt
concept was presented in this section. The user became
familiar with models, views and delegates as well as learned
how to interact by learning item view widgets. The Model
View architecture can be used to build and implement
applications with the use of this information. The section
concluded with more details, illustrated with useful
illustrations, on key QFrame, QAbstractScrollArea and
QAbstractItemView features. In conclusion, the goal of this
section on item view widgets in Qt Designer to explain the
qualities, features and customization possibilities was
successfully attained.