-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainmenu.py
More file actions
342 lines (285 loc) · 10.3 KB
/
Copy pathmainmenu.py
File metadata and controls
342 lines (285 loc) · 10.3 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from __future__ import annotations
import ctypes
import logging
import sys
from typing import List, Optional, Protocol
from PyQt6.QtCore import QEvent, QObject, QPoint, QSize, Qt, pyqtSignal
from PyQt6.QtGui import QRegion
from PyQt6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QListWidget,
QListWidgetItem,
QStyledItemDelegate,
QVBoxLayout,
QWidget,
)
from combo_popup import _disable_windows_rounded_corners
LOGGER = logging.getLogger(__name__)
MENU_POPUP_STYLE = """
QFrame#MenuPopup {
background-color: #202020;
border: none;
border-radius: 0px;
}
QListWidget {
background-color: #202020;
color: #D6D6D6;
border: none;
border-radius: 0px;
outline: 0px;
padding: 0px;
font: 10pt "Segoe UI";
}
QListWidget::item {
min-height: 32px;
padding: 0px 24px 0px 10px;
border: none;
border-radius: 0px;
color: #D6D6D6;
background-color: transparent;
}
QListWidget::item:selected {
background-color: #202020;
color: #D6D6D6;
}
QListWidget::item:hover {
background-color: #5B3A8C;
}
QScrollBar {
width: 0px;
height: 0px;
border: none;
background: transparent;
}
"""
class _MenuItemDelegate(QStyledItemDelegate):
"""Delegate that renders shortcut text aligned to the right."""
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
def sizeHint(self, option, index) -> QSize: # noqa: N802
return QSize(option.rect.width(), 32)
def paint(self, painter, option, index) -> None: # noqa: N802
super().paint(painter, option, index)
shortcut = index.data(Qt.ItemDataRole.UserRole + 1)
if not shortcut:
return
from PyQt6.QtGui import QColor, QFontMetrics
painter.save()
painter.setPen(QColor("#6a6a72"))
painter.setFont(option.font)
fm = QFontMetrics(option.font)
text_rect = option.rect.adjusted(0, 0, -10, 0)
painter.drawText(text_rect, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, str(shortcut))
painter.restore()
class _MenuPopup(QFrame):
"""Frameless popup that looks identical to the combo popup."""
itemActivated = pyqtSignal(int)
closed = pyqtSignal()
def __init__(self, items: List[str], shortcuts: List[str], parent: Optional[QWidget] = None) -> None:
super().__init__(
parent,
Qt.WindowType.Tool
| Qt.WindowType.FramelessWindowHint
| Qt.WindowType.NoDropShadowWindowHint,
)
self.setObjectName("MenuPopup")
self.setFrameShape(QFrame.Shape.NoFrame)
self.setStyleSheet(MENU_POPUP_STYLE)
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
self._list = QListWidget(self)
self._list.setFrameShape(QFrame.Shape.NoFrame)
self._list.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self._list.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self._list.setSpacing(0)
self._list.setStyleSheet(MENU_POPUP_STYLE)
self._list.setItemDelegate(_MenuItemDelegate(self._list))
for i, text in enumerate(items):
item = QListWidgetItem(text)
item.setData(Qt.ItemDataRole.UserRole, i)
item.setData(Qt.ItemDataRole.UserRole + 1, shortcuts[i] if i < len(shortcuts) else "")
item.setSizeHint(QSize(200, 32))
self._list.addItem(item)
self._list.itemClicked.connect(self._on_click)
root.addWidget(self._list)
height = self._list.count() * 32
self.setFixedSize(220, height)
def _on_click(self, item: QListWidgetItem) -> None:
row = item.data(Qt.ItemDataRole.UserRole)
if isinstance(row, int):
self.itemActivated.emit(row)
self.close()
def keyPressEvent(self, event) -> None: # noqa: N802
if event.key() == Qt.Key.Key_Escape:
self.close()
return
super().keyPressEvent(event)
class _MenuButton(QLabel):
"""Clickable label that acts as a menu bar item."""
triggered = pyqtSignal()
_STYLE_NORMAL = (
"background-color: transparent !important;"
"padding: 6px 12px;"
"border: none;"
"border-radius: 0px;"
"color: #D6D6D6;"
"font: 10pt 'Segoe UI';"
)
_STYLE_HOVER = (
"background-color: #5B3A8C !important;"
"padding: 6px 12px;"
"border: none;"
"border-radius: 0px;"
"color: #D6D6D6;"
"font: 10pt 'Segoe UI';"
)
def __init__(self, text: str, parent: Optional[QWidget] = None) -> None:
super().__init__(text, parent)
self._hovered = False
self._popup: _MenuPopup | None = None
self._event_filter_installed = False
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setStyleSheet(self._STYLE_NORMAL)
def _update_style(self) -> None:
active = self._hovered or (self._popup is not None and self._popup.isVisible())
self.setStyleSheet(self._STYLE_HOVER if active else self._STYLE_NORMAL)
def enterEvent(self, event) -> None: # noqa: N802
self._hovered = True
self._update_style()
def leaveEvent(self, event) -> None: # noqa: N802
self._hovered = False
self._update_style()
def mousePressEvent(self, event) -> None: # noqa: N802
if self._popup is not None and self._popup.isVisible():
self._close_popup()
event.accept()
return
self._show_popup()
event.accept()
def _show_popup(self) -> None:
if self._popup is not None and self._popup.isVisible():
self._close_popup()
return
actions = self._actions
if not actions:
return
texts: List[str] = []
shortcuts: List[str] = []
for act in actions:
if act is None:
continue
texts.append(act.text())
sc = act.shortcut().toString()
shortcuts.append(sc)
popup = _MenuPopup(texts, shortcuts)
popup.itemActivated.connect(lambda idx: self._activate_action(idx))
pos = self.mapToGlobal(QPoint(0, self.height()))
popup.move(pos)
self._popup = popup
popup.closed.connect(self._on_popup_closed)
popup.destroyed.connect(self._on_popup_closed)
app = QApplication.instance()
if app is not None and not self._event_filter_installed:
app.installEventFilter(self)
self._event_filter_installed = True
_disable_windows_rounded_corners(popup)
popup.show()
_disable_windows_rounded_corners(popup)
self._update_style()
popup.setMask(QRegion(popup.rect()))
def _activate_action(self, index: int) -> None:
action = self._nth_action(index)
if action is not None and action.isEnabled():
action.trigger()
self._close_popup()
def _nth_action(self, index: int):
actions = self._actions
real = [a for a in actions if a is not None]
if 0 <= index < len(real):
return real[index]
return None
def _close_popup(self) -> None:
popup = self._popup
self._popup = None
if popup is not None:
popup.close()
popup.deleteLater()
app = QApplication.instance()
if app is not None and self._event_filter_installed:
app.removeEventFilter(self)
self._event_filter_installed = False
self._update_style()
def _on_popup_closed(self) -> None:
self._close_popup()
def eventFilter(self, watched, event) -> bool: # noqa: N802
if self._popup is None or not self._popup.isVisible():
return False
if event.type() == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
self._close_popup()
return True
if event.type() != QEvent.Type.MouseButtonPress:
return False
pos = event.globalPosition().toPoint()
clicked = QApplication.widgetAt(pos)
if clicked is None:
self._close_popup()
return False
if clicked is self or self.isAncestorOf(clicked):
return False
if self._popup is not None and (clicked is self._popup or self._popup.isAncestorOf(clicked)):
return False
self._close_popup()
return False
class FileActionProvider(Protocol):
"""Protocol describing the actions required for top-level menus."""
act_file_new: object
act_file_open: object
act_file_save: object
act_file_import_txt: object
act_file_export_txt: object
act_file_export_json: object
act_language_english: object
act_language_russian: object
act_edit_undo: object
act_edit_redo: object
class MainMenuBar(QWidget):
"""Application menu bar with fully custom popup menus."""
def __init__(self, parent: QWidget, actions: FileActionProvider) -> None:
super().__init__(parent)
self.setFixedHeight(32)
self.setStyleSheet("background: #202020; border: none;")
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self._file_btn = _MenuButton("")
self._edit_btn = _MenuButton("")
self._lang_btn = _MenuButton("")
self._file_btn._actions = [
actions.act_file_new,
actions.act_file_open,
actions.act_file_save,
None, # separator
actions.act_file_import_txt,
actions.act_file_export_txt,
actions.act_file_export_json,
]
self._edit_btn._actions = [
actions.act_edit_undo,
actions.act_edit_redo,
]
self._lang_btn._actions = [
actions.act_language_english,
actions.act_language_russian,
]
layout.addWidget(self._file_btn)
layout.addWidget(self._edit_btn)
layout.addWidget(self._lang_btn)
layout.addStretch(1)
def retranslate(self, *, file_menu_title: str, edit_menu_title: str, languages_menu_title: str) -> None:
self._file_btn.setText(file_menu_title)
self._edit_btn.setText(edit_menu_title)
self._lang_btn.setText(languages_menu_title)