ListPlace.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. from .ui_py.ui_DialogListPlace import Ui_DialogListPlace
  2. from PySide6.QtWidgets import QDialog, QListWidgetItem
  3. from PySide6.QtCore import Qt, Slot
  4. from module.WorkWithDB import connect, list_place
  5. class ListPlace(QDialog, Ui_DialogListPlace):
  6. def __init__(self, parent=None) -> None:
  7. super(ListPlace, self).__init__(parent)
  8. self.setAttribute(Qt.WA_DeleteOnClose)
  9. self.setupUi(self)
  10. self.btn_save_place.clicked.connect(self._save)
  11. self.btn_update_place.clicked.connect(self._update)
  12. self.btn_delete_place.clicked.connect(self._delete)
  13. self.list_place_widget.itemSelectionChanged.connect(
  14. self._select_item
  15. )
  16. self._load_data()
  17. @Slot()
  18. def _save(self) -> None:
  19. with connect() as conn:
  20. insert_place = list_place.insert().values(
  21. name_place = self.line_name_place.text()
  22. )
  23. conn.execute(insert_place)
  24. self._clean_line_edit()
  25. self._load_data()
  26. @Slot()
  27. def _update(self) -> None:
  28. if hasattr(self, "selected_id"):
  29. with connect() as conn:
  30. update_place = list_place.update().where(
  31. list_place.c.id == self.selected_id
  32. ).values(
  33. name_place = self.line_name_place.text()
  34. )
  35. conn.execute(update_place)
  36. self._clean_line_edit()
  37. self._load_data()
  38. @Slot()
  39. def _delete(self) -> None:
  40. if hasattr(self, "selected_id"):
  41. with connect() as conn:
  42. conn.execute(
  43. list_place.delete().where(
  44. list_place.c.id == self.selected_id
  45. )
  46. )
  47. self._clean_line_edit()
  48. self._load_data()
  49. def _clean_line_edit(self) -> None:
  50. self.line_name_place.clear()
  51. @Slot()
  52. def _select_item(self) -> None:
  53. try:
  54. id = self.list_place_widget.selectedItems()[0].id
  55. self.selected_id = int(id)
  56. with connect() as conn:
  57. place = list_place.select().where(
  58. list_place.c.id == id)
  59. place_from_db = conn.execute(place).fetchone()
  60. self.line_name_place.setText(place_from_db.name_place)
  61. except IndexError:
  62. self._clean_line_edit()
  63. @Slot()
  64. def _load_data(self) -> None:
  65. self.list_place_widget.clear()
  66. with connect() as conn:
  67. for place in conn.execute(
  68. list_place.select()
  69. ).all():
  70. self.list_place_widget.addItem(
  71. self._create_item(
  72. id=place.id,
  73. name_place=place.name_place
  74. )
  75. )
  76. def _create_item(self, id: int, name_place: str) -> None:
  77. item = QListWidgetItem(name_place)
  78. item.id = id
  79. return item