import sys
import os
import PySide6
from PySide6.QtWidgets import QApplication, QMainWindow, QDialog, QListWidgetItem, QMessageBox
from PySide6 import QtCore
from mainwindow import Ui_MainWindow
from edit_dialog import Ui_Dialog
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
dirname = os.path.dirname(PySide6.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
class EditDialog(QDialog):
def __init__(self, regions, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.btnAdd.clicked.connect(self.accept)
self.ui.btnCancel.clicked.connect(self.reject)
print(regions)
for r in regions.values():
self.ui.cmbRegions.addItem(r.title, r)
def get_data(self):
return {
"region_id": self.ui.cmbRegions.currentData().id,
"year": self.ui.txtYear.text(),
"population": self.ui.txtPopulation.text()
}
class UpdateDialog(EditDialog):
def __init__(self, regions, init_data, *args, **kwargs) -> None:
super().__init__(regions, *args, **kwargs)
self.ui.btnAdd.setText('Изменить')
self.ui.cmbRegions.setEnabled(False)
region_name = regions[init_data.region_id].title
self.ui.cmbRegions.setCurrentText(region_name)
self.ui.txtPopulation.setText(str(init_data.population))
self.ui.txtYear.setText(str(init_data.year))
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.engine = create_engine("sqlite+pysqlite:///mydatabase.db", echo=True)
self.load_regions()
self.load_years()
self.load_population()
self.ui.cmbRegions.currentIndexChanged.connect(self.load_population)
self.ui.cmbYear.currentIndexChanged.connect(self.load_population)
self.ui.btnAdd.clicked.connect(self.on_btnAdd_click)
self.ui.btnRemove.clicked.connect(self.on_btnRemove_click)
self.ui.btnEdit.clicked.connect(self.on_btnEdit_click)
def on_btnEdit_click(self):
item = self.ui.lstItems.currentItem()
init_data = item.data(QtCore.Qt.ItemDataRole.UserRole)
dialog = UpdateDialog(self.regions, init_data)
r = dialog.exec()
if r == 0:
return
data = dialog.get_data()
with Session(self.engine) as s:
query = """
UPDATE populations
SET year = :y, population = :p
WHERE id = :id
"""
s.execute(text(query), {
"y": data['year'],
"p": data['population'],
"id": init_data.id,
})
s.commit()
self.load_population()
self.load_years()
def on_btnRemove_click(self):
item = self.ui.lstItems.currentItem()
data = item.data(QtCore.Qt.ItemDataRole.UserRole)
r = QMessageBox.question(self, "Подтверждение", "Точно ли хотите удалить запись?")
if r == QMessageBox.StandardButton.No:
return
with Session(self.engine) as s:
query = """
DELETE
FROM populations
WHERE id = :id
"""
s.execute(text(query), {"id": data.id})
s.commit()
self.load_population()
self.load_years()
def on_btnAdd_click(self):
dialog = EditDialog(self.regions)
r = dialog.exec()
if r == 0:
return
data = dialog.get_data()
with Session(self.engine) as s:
query = """
INSERT INTO populations(region_id, year, population)
VALUES (:rid, :y, :p)
"""
s.execute(text(query), {
"rid": data['region_id'],
"y": data['year'],
"p": data['population'],
})
s.commit()
self.load_population()
self.load_years()
def load_population(self):
regions_data = self.ui.cmbRegions.currentData()
if regions_data:
region_id = self.ui.cmbRegions.currentData().id
else:
region_id = 0
year = self.ui.cmbYear.currentText()
self.ui.lstItems.clear()
with Session(self.engine) as s:
query = """
SELECT *
FROM populations
WHERE (:rid = 0 OR region_id = :rid)
AND (:y = '-' OR year = :y)
ORDER BY year DESC
"""
rows = s.execute(text(query), {"rid": region_id, "y": year})
for r in rows:
region_name = self.regions[r.region_id].title
item = QListWidgetItem(f"{region_name} {r.year} {r.population}")
item.setData(QtCore.Qt.ItemDataRole.UserRole, r)
self.ui.lstItems.addItem(item)
def load_regions(self):
self.regions = {}
with Session(self.engine) as s:
query = """
SELECT *
FROM regions
"""
rows = s.execute(text(query))
for r in rows:
self.regions[r.id] = r
self.ui.cmbRegions.addItem("-")
for r in self.regions.values():
self.ui.cmbRegions.addItem(r.title, r)
def load_years(self):
self.ui.cmbYear.clear()
self.ui.cmbYear.addItem("-")
with Session(self.engine) as s:
query = """
SELECT DISTINCT year
FROM populations
ORDER BY 1 DESC
"""
rows = s.execute(text(query))
for r in rows:
self.ui.cmbYear.addItem(str(r.year))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())