-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombo_popup.py
More file actions
214 lines (183 loc) · 6.33 KB
/
Copy pathcombo_popup.py
File metadata and controls
214 lines (183 loc) · 6.33 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
"""QComboBox helpers for a compact non-native popup."""
from __future__ import annotations
import ctypes
import logging
import sys
from typing import Optional
from PyQt6.QtCore import QEvent, QPoint, QSize, Qt
from PyQt6.QtGui import QRegion
from PyQt6.QtWidgets import (
QApplication,
QComboBox,
QFrame,
QListWidget,
QListWidgetItem,
QStyledItemDelegate,
QVBoxLayout,
QWidget,
)
LOGGER = logging.getLogger(__name__)
POPUP_STYLE = """
QFrame#ComboPopup {
background: #202020;
border: none;
border-radius: 0px;
}
QListWidget {
background: #202020;
color: #D6D6D6;
border: none;
border-radius: 0px;
outline: 0px;
padding: 0px;
font: 10pt "Segoe UI";
}
QListWidget::item {
min-height: 32px;
padding: 0px 10px;
border: none;
border-radius: 0px;
}
QListWidget::item:selected {
background: #202020;
color: #D6D6D6;
}
QListWidget::item:hover {
background: #5B3A8C;
}
QScrollBar {
width: 0px;
height: 0px;
border: none;
background: transparent;
}
"""
class CompactComboItemDelegate(QStyledItemDelegate):
def sizeHint(self, option, index) -> QSize: # noqa: N802 - Qt API name
size = super().sizeHint(option, index)
return QSize(size.width(), 32)
def _disable_windows_rounded_corners(widget: QFrame) -> None:
if sys.platform != "win32":
return
try:
preference = ctypes.c_int(1) # DWMWCP_DONOTROUND
ctypes.windll.dwmapi.DwmSetWindowAttribute(
int(widget.winId()),
33, # DWMWA_WINDOW_CORNER_PREFERENCE
ctypes.byref(preference),
ctypes.sizeof(preference),
)
except Exception as exc: # noqa: BLE001
LOGGER.debug("DwmSetWindowAttribute failed: %s", exc)
class SquarePopupComboBox(QComboBox):
"""QComboBox with a compact square popup instead of the native rounded one."""
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setMaxVisibleItems(20)
self._popup: QFrame | None = None
self._event_filter_installed = False
def mousePressEvent(self, event) -> None: # noqa: N802 - Qt API name
if self._popup is not None and self._popup.isVisible():
self._close_popup()
event.accept()
return
self.showPopup()
event.accept()
def eventFilter(self, watched, event) -> bool: # noqa: N802 - Qt API name
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 clicked is self._popup or self._popup.isAncestorOf(clicked):
return False
self._close_popup()
return False
def showPopup(self) -> None:
if self.count() == 0:
return
if self._popup is not None and self._popup.isVisible():
self._close_popup()
return
if self._popup is not None:
self._close_popup()
popup = QFrame(
None,
Qt.WindowType.Tool
| Qt.WindowType.FramelessWindowHint
| Qt.WindowType.NoDropShadowWindowHint,
)
popup.setObjectName("ComboPopup")
popup.setFrameShape(QFrame.Shape.NoFrame)
popup.setStyleSheet(POPUP_STYLE)
popup.setFont(self.font())
layout = QVBoxLayout(popup)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
items = QListWidget(popup)
items.setFrameShape(QFrame.Shape.NoFrame)
items.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
items.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
items.setSpacing(0)
items.setFont(self.font())
items.setItemDelegate(CompactComboItemDelegate(items))
items.setStyleSheet(POPUP_STYLE)
current_row = self.currentIndex()
for row in range(self.count()):
if row == current_row:
continue
item = QListWidgetItem(self.itemText(row))
item.setFont(self.font())
item.setData(Qt.ItemDataRole.UserRole, row)
item.setSizeHint(QSize(self.width(), 32))
items.addItem(item)
if items.count() == 0:
popup.deleteLater()
return
def activate(item: QListWidgetItem) -> None:
row = item.data(Qt.ItemDataRole.UserRole)
self._close_popup()
if isinstance(row, int):
self.setCurrentIndex(row)
items.itemClicked.connect(activate)
layout.addWidget(items)
visible_count = min(items.count(), self.maxVisibleItems())
popup.setFixedSize(self.width(), visible_count * 32)
popup.move(self.mapToGlobal(QPoint(0, self.height())))
self._popup = popup
popup.destroyed.connect(self._on_popup_destroyed)
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)
popup.setMask(QRegion(popup.rect()))
items.setMask(QRegion(items.rect()))
items.viewport().setMask(QRegion(items.viewport().rect()))
def _close_popup(self) -> None:
popup = self._popup
self._popup = None
app = QApplication.instance()
if app is not None and self._event_filter_installed:
app.removeEventFilter(self)
self._event_filter_installed = False
if popup is not None:
popup.hide()
popup.deleteLater()
def _on_popup_destroyed(self, *_args) -> None:
self._popup = None
app = QApplication.instance()
if app is not None and self._event_filter_installed:
app.removeEventFilter(self)
self._event_filter_installed = False