Python desktop application


Simple Python desktop application


This is a continuation to my previous tutorial (Python GUI using PyQt). Anyway I will recap the tutorial on how to develop Python Desktop Application using 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., 

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

Now, goto your terminal and run 

          python tables.py

The above code generates the following output −



Generating an executable (.exe) file:

You can generate a .exe file using `Pyinstaller` library.

PyInstaller freezes (packages) Python applications into stand-alone executables, under Windows, GNU/Linux, Mac OS X, FreeBSD, Solaris and AIX.

Install PyInstaller from PyPI:

pip install pyinstaller


Go to your program’s directory and run:

      pyinstaller yourprogram.py

This will generate the bundle in a subdirectory called dist.

Note: 
The above pyinstaller command will generate executable file only for `yourprogram.py`. In order to generate executable file for both database file and your script file, run the below command:

pyinstaller -w --add-data "sample.db;." tables.py

This will first create a .spec file that lists sample.db as a file to be included in your build. The created .spec file will then be used to run the build.

The -w option prevents a console from being displayed when you run the .exe file that will be created.

Alternatively, you can first create just the .spec file and then modify it to list the data files that should be included. The .spec file for script.py is created using:

pyi-makespec tables.py

Then, within the .spec file created, you can modify the datas field:

a = Analysis(...
    datas=[ ('sample.db', '.') ],
    ...

)

Comments

  1. Thank you for content. I like it and my site is different for your site. please visit my site. เครดิตฟรี

    ReplyDelete

Post a Comment

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb