Saturday, May 29, 2021

Refactoring PyQT5 code of OldProgramer for Complete CRUD App on PostgreSQL 13.2 (F34 Server)

 That is an immediate follow up for post Setup PostgreSQL 13.2 and PyQT5 to run CRUD App in PyCharm 2021.1.1 on F34

Method updating table students has been added to original code and front-end window has been updated as well to have one more button to invoke "Update table" on the fly 

#!/usr/bin/python3

import sys

import psycopg2

from PyQt5.QtWidgets import QTableWidget, QApplication, QMainWindow, QTableWidget 

from PyQt5.QtWidgets import QTableWidgetItem, QWidget, QPushButton, QLineEdit

from PyQt5 import QtGui

class MyWidget(QWidget):

    def __init__(self):

        super().__init__()

        self.con()

        self.setGeometry(100, 100, 500, 600)

        self.setWindowTitle('Scores List')

        self.tb = Tb(self)

        self.btn = QPushButton('Refresh View', self)

        self.btn.resize(150, 40)

        self.btn.move(300, 10)

        self.btn.clicked.connect(self.upd)

        self.idp = QLineEdit(self)

        self.idp.resize(150, 40)

        self.idp.move(300, 60)

        self.idp.setReadOnly(True)

        self.fio = QLineEdit(self)

        self.fio.resize(150, 40)

        self.fio.move(300, 110)

        self.oce = QLineEdit(self)

        self.oce.resize(150, 40)

        self.oce.move(300, 160)

        self.btn = QPushButton('Add row', self)

        self.btn.resize(150, 40)

        self.btn.move(300, 210)

        self.btn.clicked.connect(self.ins)

# update button added by B.D. 

        self.btn = QPushButton('Update row', self)

        self.btn.resize(150, 40)

        self.btn.move(300, 260)

        self.btn.clicked.connect(self.change)

# delete button moved by B.D. 

        self.btn = QPushButton('Delete row', self)

        self.btn.resize(150, 40)

        self.btn.move(300, 310)

        self.btn.clicked.connect(self.dels)

# connect to datatabase 

    def con(self):

        self.conn = psycopg2.connect(user = "postgres",

                              password = "*******",

                              host = "192.168.0.14",

                              port = "5432",

                              database = "db1")

        self.cur = self.conn.cursor()

    def upd(self):

        self.conn.commit()

        self.tb.updt()

        self.idp.setText('')

        self.fio.setText('')

        self.oce.setText('')

    def ins(self):

        fio, oce = self.fio.text(), self.oce.text()

        try:

            self.cur.execute("insert into students (name, ocenka) values (%s,%s)",(fio,oce))

        except:

            pass

        self.upd()

# row update added by B.D. 

    def change(self):

        fio, oce = self.fio.text(), self.oce.text()

        try:

            ids = int(self.idp.text()) 

        except:

            return

        self.cur.execute("update students set name=%s,ocenka=%s where id=%s",(fio,oce,ids,))

        self.upd()

# delete record from table 

    def dels(self):

        try:

            ids = int(self.idp.text()) # line identifier

        except:

            return

        self.cur.execute("delete from students where id=%s",(ids,))

        self.upd()

class Tb(QTableWidget):

    def __init__(self, wg):

        self.wg = wg  # remember window to show table 

        super().__init__(wg)

        self.setGeometry(10, 10, 280, 500)

        self.setColumnCount(3)

        self.verticalHeader().hide();

        self.updt() # обновить таблицу

        self.setEditTriggers(QTableWidget.NoEditTriggers)  

        self.cellClicked.connect(self.cellClick)  # catch mouse click on table 

    def updt(self):

        self.clear()

        self.setRowCount(0);

        self.setHorizontalHeaderLabels(['id', 'Name', 'Score']) 

        self.wg.cur.execute("select * from students order by id")

        rows = self.wg.cur.fetchall()

        i = 0

        for elem in rows:

            self.setRowCount(self.rowCount() + 1)

            j = 0

            for t in elem: # fill inside the line

                self.setItem(i, j, QTableWidgetItem(str(t).strip()))

                j += 1

            i += 1

        self.resizeColumnsToContents()

# Reaction on mouse click inside table 

    def cellClick(self, row, col): # row - row number, col - column number 

        self.wg.idp.setText(self.item(row, 0).text())

        self.wg.fio.setText(self.item(row, 1).text().strip())

        self.wg.oce.setText(self.item(row, 2).text().strip())

app = QApplication(sys.argv)

ex = MyWidget()

ex.show()

sys.exit(app.exec_())


















































No comments:

Post a Comment