我用PyQt5的sqlite3和QTableWidget创建了一个小型数据库。可以添加,编辑和删除记录。当我想删除一个记录时,我在QTableWidget中选择它,然后单击“删除”按钮,此后,它将显示另一个带有记录的窗口以及两个按钮“确定”和“取消”。 单击“确定”将从数据库中删除记录,然后使用self.close()指令,窗口也应关闭,但它没有关闭,我也不明白原因。即使您想通过单击关闭的X图标来关闭鼠标窗口,也无法执行。
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QPushButton,QDialog,QHBoxLayout,QVBoxLayout,QGridLayout,QLabel,QWidget,QLineEdit,QDialogButtonBox,QTableWidget,QTableWidgetItem
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtCore import Qt,QPoint,QPointF,QRect,QDateTime,QDate,QTime
import sqlite3
import datetime
import ctypes as ct
import itertools
import re
class Window(QMainWindow):
def __init__(self):
super().__init__()
title = "SQlite3 embeded in QTableWidget";left=100;top=100;width=1200;height=800
self.setWindowTitle(title)
self.setGeometry(left,top,width,height)
self.libswiss = ct.CDLL("/usr/lib/libswe.so")
self.libswiss.swe_set_ephe_path.argtypes = [ct.c_wchar_p]
self.libswiss.swe_set_ephe_path.restype = None
path = "/usr/share/ephe"
self.libswiss.swe_set_ephe_path(path)
self.libswiss.swe_julday.argtypes = [ct.c_int,ct.c_int,ct.c_int,ct.c_double,ct.c_int]
self.libswiss.swe_julday.restype = ct.c_double
self.libswiss.swe_revjul.argtypes = [ct.c_double,ct.c_int,ct.POINTER(ct.c_int),ct.POINTER(ct.c_int),ct.POINTER(ct.c_int),ct.POINTER(ct.c_double)]
self.libswiss.swe_revjul.restype = None
self.CreaPulsanteDatabase()
self.show()
def CreaPulsanteDatabase(self):
button = QPushButton("Database", self)
button.setGeometry(QtCore.QRect(30,100,200,80))
button.clicked.connect(self.Database)
def Database(self):
self.d = DialogDatabase()
self.d.Crea_FinestraDatabase(1160,700)
self.d.Crea_Oggetti()
self.d.Crea_TableWidget_Persone()
self.d.Crea_Layout(table)
self.d.Apri_Database_Persone()
self.d.LoadDatabase_Persone()
def closeEvent(self,event):
self.libswiss.swe_close.argtypes = None
self.libswiss.swe_close.restype = None
self.libswiss.swe_close()
def strData2GiornoGiuliano(self,strdata):
pattern = "^\d+"
result = re.findall(pattern,strdata)
giorno = int(result[0])
pattern = "/(.*?)/"
result = re.findall(pattern,strdata)
mese = int(result[0])
pattern = "\d\d\d\d$"
result = re.findall(pattern,strdata)
anno = int(result[0])
oraUT=0.0;gregflag=1
GiornoGiuliano = self.libswiss.swe_julday(anno,mese,giorno,oraUT,gregflag)
return(GiornoGiuliano)
class DialogDatabase(QDialog):
def Crea_FinestraDatabase(self,width,height):
title = "Database";left=600;top=360
self.setWindowTitle(title)
self.setGeometry(left,top,width,height)
self.setStyleSheet('background-color:lightyellow')
self.iter = itertools.cycle([" ASC"," DESC"])
self.show()
def Apri_Database_Persone(self):
global conn,curs
conn = sqlite3.connect('Persone.db')
curs = conn.cursor()
curs.execute('CREATE TABLE IF NOT EXISTS Persone (Cognome TEXT, Nome TEXT, Data REAL, Ora TEXT, Fuso TEXT, Località TEXT, Long TEXT, Lat TEXT, Professione TEXT)')
def LoadDatabase_Persone(self):
while (table.rowCount() > 0):
table.removeRow(0)
w = Window()
res = curs.execute('SELECT * FROM Persone')
for row_index, row_data in enumerate(res):
table.insertRow(row_index)
for colm_index, colm_data in enumerate(row_data):
if colm_index == 2:
anno=ct.c_int(0);mese=ct.c_int(0);giorno=ct.c_int(0);oraUT=ct.c_double(0.0)
w.libswiss.swe_revjul(colm_data,1,anno,mese,giorno,oraUT)
strdata = str(giorno.value) + "/" + str(mese.value) + "/" + str(anno.value)
table.setItem(row_index,colm_index,QTableWidgetItem(strdata))
else:
table.setItem(row_index,colm_index,QTableWidgetItem(str(colm_data)))
def Crea_Oggetti(self):
self.btnEdit = QPushButton("Edit",self)
self.btnEdit.setAutoDefault(False)
self.btnEdit.clicked.connect(self.click_Edit)
self.btnDelete = QPushButton("Delete",self)
self.btnDelete.setAutoDefault(False)
self.btnDelete.clicked.connect(self.click_Delete)
self.btnAdd = QPushButton("Add",self)
self.btnAdd.setAutoDefault(False)
self.btnAdd.clicked.connect(self.click_Add)
def Crea_TableWidget_Persone(self):
global table
table = QTableWidget(self)
table.setRowCount(200)
table.setColumnCount(9)
table.setStyleSheet("background-color:rgb(203,255,203)")
self.HeaderPersone = ["Cognome","Nome","Data","Ora","Fuso","Località","Long","Lat","Professione"]
table.setHorizontalHeaderLabels(self.HeaderPersone)
table.setSortingEnabled(0)
def Crea_Layout(self,TT):
hbox1 = QHBoxLayout()
hbox1.addStretch(1)
hbox1.addWidget(self.btnEdit)
hbox1.addWidget(self.btnDelete)
hbox1.addWidget(self.btnAdd)
vbox3 = QVBoxLayout()
vbox3.addLayout(hbox1)
vbox3.addWidget(TT)
self.setLayout(vbox3)
def click_Edit(self):
pass
def click_Delete(self):
res = curs.execute('SELECT * FROM Persone')
for row in enumerate(res):
if row[0] == table.currentRow():
dati = row[1]
self.Cognome=dati[0];self.Nome=dati[1];self.Data=dati[2];self.Ora=dati[3];self.Fuso=dati[4];self.Località=dati[5];self.Long=dati[6];self.Lat=dati[7];self.Professione=dati[8]
self.da = Delete_Persone()
self.da.Crea_FinestraDeletePersone(1160)
self.da.Crea_OggettieLayoutDeletePersone(self.Cognome,self.Nome,self.Data,self.Ora,self.Fuso,self.Località,self.Long,self.Lat,self.Professione) # Crea gli Oggetti ed il Layout di Delete Persone, poi se premi Pulsante Ok
def click_Add(self):
self.a = Add_Persone()
self.a.Crea_FinestraAddPersone(1160)
self.a.Crea_OggettieLayoutAddPersone()
class Add_Persone(DialogDatabase):
def Crea_FinestraAddPersone(self,width):
title = "Aggiungi un Record al Database Persone";left=600;top=1120;height=80
self.setWindowTitle(title)
self.setGeometry(left,top,width,height)
self.setStyleSheet('background-color:white')
self.show()
def Crea_OggettieLayoutAddPersone(self):
Cognomelabel = QLabel("Cognome",self)
Nomelabel = QLabel("Nome",self)
Datalabel = QLabel("Data",self)
Oralabel = QLabel("Ora",self)
Fusolabel = QLabel("Fuso",self)
Localitàlabel = QLabel("Località",self)
Longlabel = QLabel("Long",self)
Latlabel = QLabel("Lat",self)
Professionelabel = QLabel("Professione",self)
self.CognomelineEdit = QLineEdit(self)
self.CognomelineEdit.returnPressed.connect(self.pressInsert)
self.NomelineEdit = QLineEdit(self)
self.NomelineEdit.returnPressed.connect(self.pressInsert)
self.DatalineEdit = QLineEdit(self)
self.DatalineEdit.setToolTip("DD/MM/YYYY")
self.DatalineEdit.setStyleSheet('QToolTip {font-size:9.4pt;background-color:black; color:white; border:black solid 1px}')
self.DatalineEdit.returnPressed.connect(self.pressInsert)
self.OralineEdit = QLineEdit(self)
self.OralineEdit.setToolTip("HH:MM")
self.OralineEdit.setStyleSheet('QToolTip {font-size:9.4pt;background-color:black; color:white; border:black solid 1px}')
self.OralineEdit.returnPressed.connect(self.pressInsert)
self.FusolineEdit = QLineEdit(self)
self.FusolineEdit.setToolTip("se Est metti segno Negativo, per es. -2.0")
self.FusolineEdit.setStyleSheet('QToolTip {font-size:9.4pt;background-color:black; color:white; border:black solid 1px}')
self.FusolineEdit.returnPressed.connect(self.pressInsert)
self.LocalitàlineEdit = QLineEdit(self)
self.LocalitàlineEdit.returnPressed.connect(self.pressInsert)
self.LonglineEdit = QLineEdit(self)
self.LonglineEdit.setToolTip("per es. 12E36 (12 gradi e 36 minuti Est)\nper es. 118W52 (118 gradi e 52 minuti Ovest)")
self.LonglineEdit.setStyleSheet('QToolTip {font-size:9.4pt;background-color:black; color:white; border:black solid 1px}')
self.LonglineEdit.returnPressed.connect(self.pressInsert)
self.LatlineEdit = QLineEdit(self)
self.LatlineEdit.setToolTip("per es. 42N03 (42 gradi e 3 minuti Nord)\nper es. 26S47 (26 gradi e 47 minuti Sud)")
self.LatlineEdit.setStyleSheet('QToolTip {font-size:9.4pt;background-color:black; color:white; border:black solid 1px}')
self.LatlineEdit.returnPressed.connect(self.pressInsert)
self.ProfessionelineEdit = QLineEdit(self)
self.ProfessionelineEdit.returnPressed.connect(self.pressInsert)
grid = QGridLayout()
grid.addWidget(Cognomelabel,0,0,QtCore.Qt.AlignCenter)
grid.addWidget(self.CognomelineEdit,1,0)
grid.addWidget(Nomelabel,0,1,QtCore.Qt.AlignCenter)
grid.addWidget(self.NomelineEdit,1,1)
grid.addWidget(Datalabel,0,2,QtCore.Qt.AlignCenter)
grid.addWidget(self.DatalineEdit,1,2)
grid.addWidget(Oralabel,0,3,QtCore.Qt.AlignCenter)
grid.addWidget(self.OralineEdit,1,3)
grid.addWidget(Fusolabel,0,4,QtCore.Qt.AlignCenter)
grid.addWidget(self.FusolineEdit,1,4)
grid.addWidget(Localitàlabel,0,5,QtCore.Qt.AlignCenter)
grid.addWidget(self.LocalitàlineEdit,1,5)
grid.addWidget(Longlabel,0,6,QtCore.Qt.AlignCenter)
grid.addWidget(self.LonglineEdit,1,6)
grid.addWidget(Latlabel,0,7,QtCore.Qt.AlignCenter)
grid.addWidget(self.LatlineEdit,1,7)
grid.addWidget(Professionelabel,0,8,QtCore.Qt.AlignCenter)
grid.addWidget(self.ProfessionelineEdit,1,8)
self.setLayout(grid)
def pressInsert(self):
w = Window()
Cognome = self.CognomelineEdit.text()
Nome = self.NomelineEdit.text()
GiornoGiuliano = w.strData2GiornoGiuliano(self.DatalineEdit.text())
Ora = self.OralineEdit.text()
Fuso = self.FusolineEdit.text()
Località = self.LocalitàlineEdit.text()
Long = self.LonglineEdit.text()
Lat = self.LatlineEdit.text()
Professione = self.ProfessionelineEdit.text()
curs.execute('INSERT INTO Persone VALUES (?,?,?,?,?,?,?,?,?)',(Cognome,Nome,GiornoGiuliano,Ora,Fuso,Località,Long,Lat,Professione))
conn.commit()
self.CognomelineEdit.setText("");self.NomelineEdit.setText("");self.DatalineEdit.setText("");self.OralineEdit.setText("");self.FusolineEdit.setText("");self.LocalitàlineEdit.setText("");self.LonglineEdit.setText("");self.LatlineEdit.setText("");self.ProfessionelineEdit.setText("")
self.CognomelineEdit.setFocus()
self.d2 = DialogDatabase()
self.d2.LoadDatabase_Persone()
class Delete_Persone(DialogDatabase):
def Crea_FinestraDeletePersone(self,width):
title = "Elimina il Record dal Database Persone";left=600;top=1120;height=80
self.setWindowTitle(title)
self.setGeometry(left,top,width,height)
self.setStyleSheet('background-color:white')
self.show()
def Crea_OggettieLayoutDeletePersone(self,Cognome,Nome,Data,Ora,Fuso,Località,Long,Lat,Professione):
self.Cognome=Cognome;self.Nome=Nome;self.Data=Data;self.Ora=Ora;self.Fuso=Fuso;self.Località=Località;self.Long=Long;self.Lat=Lat;self.Professione=Professione
anno=ct.c_int(0);mese=ct.c_int(0);giorno=ct.c_int(0);oraUT=ct.c_double(0.0)
w = Window()
w.libswiss.swe_revjul(Data,1,anno,mese,giorno,oraUT)
strdata = str(giorno.value) + "/" + str(mese.value) + "/" + str(anno.value)
Cognomelabel = QLabel("Cognome",self)
Nomelabel = QLabel("Nome",self)
Datalabel = QLabel("Data",self)
Oralabel = QLabel("Ora",self)
Fusolabel = QLabel("Fuso",self)
Localitàlabel = QLabel("Località",self)
Longlabel = QLabel("Long",self)
Latlabel = QLabel("Lat",self)
Professionelabel = QLabel("Professione",self)
self.CognomelineEdit = QLineEdit(self)
self.CognomelineEdit.setText(Cognome)
self.CognomelineEdit.setReadOnly(1)
self.NomelineEdit = QLineEdit(self)
self.NomelineEdit.setText(Nome)
self.NomelineEdit.setReadOnly(1)
self.DatalineEdit = QLineEdit(self)
self.DatalineEdit.setText(strdata)
self.DatalineEdit.setReadOnly(1)
self.OralineEdit = QLineEdit(self)
self.OralineEdit.setText(Ora)
self.OralineEdit.setReadOnly(1)
self.FusolineEdit = QLineEdit(self)
self.FusolineEdit.setText(Fuso)
self.FusolineEdit.setReadOnly(1)
self.LocalitàlineEdit = QLineEdit(self)
self.LocalitàlineEdit.setText(Località)
self.LocalitàlineEdit.setReadOnly(1)
self.LonglineEdit = QLineEdit(self)
self.LonglineEdit.setText(Long)
self.LonglineEdit.setReadOnly(1)
self.LatlineEdit = QLineEdit(self)
self.LatlineEdit.setText(Lat)
self.LatlineEdit.setReadOnly(1)
self.ProfessionelineEdit = QLineEdit(self)
self.ProfessionelineEdit.setText(Professione)
self.ProfessionelineEdit.setReadOnly(1)
self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.buttonbox.setOrientation(QtCore.Qt.Horizontal)
self.buttonbox.setStyleSheet('color:blue;font:bold')
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
grid = QGridLayout()
grid.addWidget(Cognomelabel,0,0,QtCore.Qt.AlignCenter)
grid.addWidget(self.CognomelineEdit,1,0)
grid.addWidget(Nomelabel,0,1,QtCore.Qt.AlignCenter)
grid.addWidget(self.NomelineEdit,1,1)
grid.addWidget(Datalabel,0,2,QtCore.Qt.AlignCenter)
grid.addWidget(self.DatalineEdit,1,2)
grid.addWidget(Oralabel,0,3,QtCore.Qt.AlignCenter)
grid.addWidget(self.OralineEdit,1,3)
grid.addWidget(Fusolabel,0,4,QtCore.Qt.AlignCenter)
grid.addWidget(self.FusolineEdit,1,4)
grid.addWidget(Localitàlabel,0,5,QtCore.Qt.AlignCenter)
grid.addWidget(self.LocalitàlineEdit,1,5)
grid.addWidget(Longlabel,0,6,QtCore.Qt.AlignCenter)
grid.addWidget(self.LonglineEdit,1,6)
grid.addWidget(Latlabel,0,7,QtCore.Qt.AlignCenter)
grid.addWidget(self.LatlineEdit,1,7)
grid.addWidget(Professionelabel,0,8,QtCore.Qt.AlignCenter)
grid.addWidget(self.ProfessionelineEdit,1,8)
grid.addWidget(self.buttonbox,2,8)
self.setLayout(grid)
def accept(self):
curs.execute('DELETE FROM Persone WHERE Cognome=? AND Nome=? AND Data=? AND Ora=? AND Fuso=? AND Località=? AND Long=? AND Lat=? AND Professione=?',(self.Cognome,self.Nome,self.Data,self.Ora,self.Fuso,self.Località,self.Long,self.Lat,self.Professione))
conn.commit()
self.d3 = DialogDatabase()
self.d3.LoadDatabase_Persone()
self.close()
def reject(self):
self.close()
class Edit_Persone(DialogDatabase):
pass
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())