-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_window.py
259 lines (214 loc) · 9.24 KB
/
main_window.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import os
from PyQt6.QtWidgets import (
QMainWindow,
QVBoxLayout,
QWidget,
QListView,
QLabel,
QHeaderView,
QTableView,
QAbstractItemView,
QMessageBox,
QPushButton,
QFileDialog,
)
from PyQt6.QtCore import (
QSize,
QItemSelectionModel,
Qt,
)
from PyQt6.QtGui import (
QStandardItemModel,
QStandardItem,
)
from PyQt6 import uic
from . import (
Deck,
Flashcard,
engine,
DeckTableModel,
DeckWidget,
PlaylistWidget,
)
from .decks_parser import DeckParser
from .tests import sample_db_data as dbtest
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.model = DeckTableModel()
# dbtest.add_sample_decks()
# dbtest.add_sample_decks_with_categories()
# dbtest.add_sample_flashcards()
# dbtest.print_all_flashcards()
dbtest.print_correct_answers()
# dbtest.add_more_sample_flashcards()
current_dir = os.path.dirname(os.path.abspath(__file__))
ui_path = os.path.join(current_dir, "ui", "main_window.ui")
uic.loadUi(ui_path, self)
self.view: QTableView = self.view
self.add_button: QPushButton = self.add_button
self.delete_button: QPushButton = self.delete_button
self.merge_button: QPushButton = self.merge_button
self.import_button: QPushButton = self.import_button
self.export_button: QPushButton = self.export_button
self.create_playlist_button: QPushButton = self.create_playlist_button
self.stats_button: QPushButton = self.stats_button
self.view.setModel(self.model)
self.view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.view.resizeColumnsToContents()
self.view.setSortingEnabled(True)
self.view.horizontalHeader().setSortIndicator(0, Qt.SortOrder.AscendingOrder)
self.selection_model = self.view.selectionModel()
self.delete_button.setEnabled(False)
self.create_playlist_button.setEnabled(False)
self.export_button.setEnabled(False)
self.merge_button.setEnabled(False)
self.stats_button.setEnabled(False)
self.setup_horizontal_header()
self.model.refresh()
self.connect_signals()
def connect_signals(self):
self.add_button.clicked.connect(self.add_deck)
self.delete_button.clicked.connect(self.delete_decks)
self.merge_button.clicked.connect(self.merge_decks)
self.create_playlist_button.clicked.connect(self.create_playlist)
self.view.doubleClicked.connect(self.open_selected_deck_widget)
self.selection_model.selectionChanged.connect(self.toggle_buttons_selection)
self.import_button.clicked.connect(self.import_decks)
self.export_button.clicked.connect(self.export_decks)
def refresh_model_and_view(self):
"""Refresh the table view and the model - called after any changes to the records in the model"""
# index = self.model.index(deck_row.row(), 1)
# self.model.dataChanged.emit(index, index)
# self.model.refresh()
# self.view.update()
# self.view.repaint()
self.model.refresh()
self.view.resizeColumnsToContents()
def setup_horizontal_header(self):
hh = self.view.horizontalHeader()
for i in range(0, self.model.columnCount()):
hh.setSectionResizeMode(i, QHeaderView.ResizeMode.ResizeToContents)
hh.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
# self.view.setColumnWidth(2, 100)
hh.setMinimumHeight(30)
bold_font = hh.font()
bold_font.setBold(True)
hh.setFont(bold_font)
hh.setHighlightSections(True)
return hh
def open_selected_deck_widget(self):
"""Open a widget in a new window with the single selected deck"""
selected_deck_rows = self.selection_model.selectedRows()
if not selected_deck_rows:
return
if len(selected_deck_rows) != 1:
return
clicked_row = selected_deck_rows[0]
selected_deck = self.model.results[clicked_row.row()]
if selected_deck is None:
log.error("Selected deck is None")
QMessageBox.critical(
self, "Error", "Selected deck not found in the database."
)
return
deck_widget = DeckWidget(selected_deck.id, clicked_row, parent=self)
deck_widget.show()
def toggle_buttons_selection(self):
"""Toggle button enabled state based on selection"""
self.delete_button.setEnabled(self.selection_model.hasSelection())
self.create_playlist_button.setEnabled(self.selection_model.hasSelection())
self.merge_button.setEnabled(
self.selection_model.hasSelection()
and len(self.selection_model.selectedRows()) >= 2
)
self.export_button.setEnabled(self.selection_model.hasSelection())
def add_deck(self):
"""Add a new empty deck with default title to the database and open related widget in a new window"""
new_deck = self.model.insertEmptyRecord()
session = self.model.session
new_deck.title = new_deck.default_title()
session.commit()
self.refresh_model_and_view()
deck_widget = DeckWidget(new_deck.id, parent=self)
deck_widget.show()
def delete_decks(self):
"""Delete selected decks from the database"""
del_rows = self.selection_model.selectedRows()
self.model._delete_rows(del_rows)
dbtest.print_all_flashcards()
def merge_decks(self):
"""Merge selected playlists into a new playlist, transfering flashcards to the new playlist and deleting the old ones"""
selected_deck_rows = self.selection_model.selectedRows()
if not selected_deck_rows or len(selected_deck_rows) < 2:
return
selected_decks = [self.model.results[row.row()] for row in selected_deck_rows]
category_ids = {deck.Category_id for deck in selected_decks}
if len(category_ids) > 1:
log.error("Selected decks must have the same category")
QMessageBox.critical(
self, "Merge error", "Selected decks must have the same category"
)
return
category_id = category_ids.pop()
selected_deck_ids = [deck.id for deck in selected_decks]
self.model.merge_decks(selected_deck_ids, category_id=category_id)
self.refresh_model_and_view()
def create_playlist(self):
"""Create a new playlist from selected decks and open the playlist widget in a new window"""
selected_deck_rows = self.selection_model.selectedRows()
if not selected_deck_rows:
return
# playlist_widget = PlaylistWidget(decks, parent=self)
selected_decks = [self.model.results[row.row()] for row in selected_deck_rows]
selected_deck_ids = [deck.id for deck in selected_decks]
playlist_widget = PlaylistWidget(selected_deck_ids, parent=self)
playlist_widget.show()
def export_decks(self):
selected_deck_rows = self.selection_model.selectedRows()
if not selected_deck_rows:
return
selected_decks = [self.model.results[row.row()] for row in selected_deck_rows]
file_dialog = QFileDialog()
file_path, _ = file_dialog.getSaveFileName(
self, "Save as", "", "JSON files (*.json)"
)
if file_path:
try:
with open(file_path, "w") as file:
decks_parser = DeckParser()
file.write(decks_parser.export_decks(selected_decks))
QMessageBox.information(
self, "Success", "JSON file saved successfully."
)
except Exception as e:
QMessageBox.critical(
self, "Error", "An error occured while saving the file."
)
log.error(f"Error while opening the file: {e}")
else:
# QMessageBox.warning(self, "Ostrzeżenie", "Nie wybrano lokalizacji pliku.")
log.warning("File path not selected.")
def import_decks(self):
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(
self, "Open file", "", "JSON files (*.json)"
)
if file_path:
try:
with open(file_path, "r") as file:
content = file.read()
decks_parser = DeckParser()
decks_parser.import_decks(content)
self.refresh_model_and_view()
except Exception as e:
QMessageBox.critical(
self, "Error", "An error occured while opening the file."
)
log.error(f"Error while opening the file: {e}")
else:
# QMessageBox.warning(self, "Ostrzeżenie", "Nie wybrano pliku.")
log.warning("File path not selected.")