Python GUI using PyQt
Create GUI application using Python PyQt5
PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library.
PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc.,
QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc.
Environments:
PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS.
Pip Install:
The latest version of PyQt is PyQt5 5.14.1. You can install pyqt using
pip install PyQt5
In this tutorial, we are going to create a simple GUI app to add and delete records in a table using SQLite database.
First, we need to create a database connection file with name `create_db.py`.
A connection with a SQLite database is established using the static method −
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sample.db')
The following script (create_db.py) creates a SQLite database sample.db with a table of usersdata populated with five records.
import sys
import os
import random
from PyQt5 import QtCore, QtWidgets, QtGui, QtSql
from PyQt5.QtWidgets import QApplication
def createDB():
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sample.db')
if not db.open():
QtWidgets.QMessageBox.critical(None, QtWidgets.qApp.tr("Cannot open database"),
QtWidgets.qApp.tr("Unable to establish a database connection.\n"
"This example needs SQLite support. "
"Click Cancel to exit."),
QtWidgets.QMessageBox.Cancel)
return False
query = QtSql.QSqlQuery()
query.exec_("create table usersdata(id int primary key, "
"firstname varchar(20), lastname varchar(20))")
query.exec_("insert into usersdata values(101, 'Roger', 'Justice')")
query.exec_("insert into usersdata values(102, 'Christiano', 'James')")
query.exec_("insert into usersdata values(103, 'Amy', 'Peter')")
query.exec_("insert into usersdata values(104, 'Sachin', 'Tendulkar')")
query.exec_("insert into usersdata values(105, 'Sri', 'Charan')")
return True
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
createDB()
Now create another file (tables.py), which shows list of all the records from the database.
import sys
import os
import random
from PyQt5 import QtCore, QtWidgets, QtGui, QtSql
from PyQt5.QtWidgets import QApplication
def initializeModel(model):
model.setTable('usersdata')
model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
model.select()
model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
model.setHeaderData(1, QtCore.Qt.Horizontal, "First name")
model.setHeaderData(2, QtCore.Qt.Horizontal, "Last name")
def createView(title, model):
view = QtWidgets.QTableView()
view.setModel(model)
view.setWindowTitle(title)
return view
def addrow():
print(model.rowCount())
ret = model.insertRows(model.rowCount(), 1)
print(ret)
def findrow(i):
delrow = i.row()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sample.db')
model = QtSql.QSqlTableModel()
delrow = -1
initializeModel(model)
view1 = createView("Table Model (View 1)", model)
view1.clicked.connect(findrow)
dlg = QtWidgets.QDialog()
layout = QtWidgets.QVBoxLayout()
layout.addWidget(view1)
button = QtWidgets.QPushButton("Add a row")
button.clicked.connect(addrow)
layout.addWidget(button)
btn1 = QtWidgets.QPushButton("del a row")
btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))
layout.addWidget(btn1)
dlg.setLayout(layout)
dlg.setWindowTitle("Simple Database App")
dlg.show()
sys.exit(app.exec_())
Let's go through above code line by line:
In the above code, `usersdata` table is used as a model and the strategy is set as
model.setTable('usersdata')
model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
model.select()
QTableView class is part of Model/View framework in PyQt. The QTableView object is created as follows −
view = QtGui.QTableView()
view.setModel(model)
view.setWindowTitle(title)
return view
This QTableView object and two QPushButton widgets are added to the top level QDialog window. Clicked() signal of add button is connected to addrow() which performs insertRow() on the model table.
button.clicked.connect(addrow)
def addrow():
print model.rowCount()
ret = model.insertRows(model.rowCount(), 1)
print ret
The Slot associated with the delete button executes a lambda function that deletes a row, which is selected by the user.
btn1.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))
The above code generates the following output −
Comments
Post a Comment