-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathcombobox.py
464 lines (401 loc) · 17 KB
/
combobox.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import sys
from typing import Optional
from AnyQt.QtCore import (
Qt, QEvent, QObject, QAbstractItemModel, QSortFilterProxyModel,
QModelIndex, QSize, QRect, QMargins, QElapsedTimer,
QTimer, QT_VERSION
)
from AnyQt.QtGui import QMouseEvent, QKeyEvent, QPainter, QPalette, QPen
from AnyQt.QtWidgets import (
QWidget, QComboBox, QLineEdit, QAbstractItemView, QListView,
QStyleOptionComboBox, QStyleOptionViewItem, QStyle, QStylePainter,
QStyledItemDelegate, QApplication
)
from orangewidget.utils import dropdown_popup_geometry
# we want to have combo box maximally 25 characters wide
MAXIMUM_CONTENTS_LENGTH = 25
class ComboBox(QComboBox):
"""
A QComboBox subclass extended to support bounded contents width hint.
Prefer to use this class in place of plain QComboBox when the used
model will possibly contain many items.
"""
def __init__(self, parent=None, **kwargs):
self.__maximumContentsLength = MAXIMUM_CONTENTS_LENGTH
super().__init__(parent, **kwargs)
self.__in_mousePressEvent = False
# Yet Another Mouse Release Ignore Timer
self.__yamrit = QTimer(self, singleShot=True)
view = self.view()
# optimization for displaying large models
if isinstance(view, QListView):
view.setUniformItemSizes(True)
view.viewport().installEventFilter(self)
def setMaximumContentsLength(self, length): # type: (int) -> None
"""
Set the maximum contents length hint.
The hint specifies the upper bound on the `sizeHint` and
`minimumSizeHint` width specified in character length.
Set to 0 or negative value to disable.
Note
----
This property does not affect the widget's `maximumSize`.
The widget can still grow depending on its `sizePolicy`.
Parameters
----------
length : int
Maximum contents length hint.
"""
if self.__maximumContentsLength != length:
self.__maximumContentsLength = length
self.updateGeometry()
def maximumContentsLength(self): # type: () -> int
"""
Return the maximum contents length hint.
"""
return self.__maximumContentsLength
def _get_size_hint(self):
sh = super().sizeHint()
if self.__maximumContentsLength > 0:
width = (
self.fontMetrics().horizontalAdvance("X") * self.__maximumContentsLength
+ self.iconSize().width() + 4
)
sh = sh.boundedTo(QSize(width, sh.height()))
return sh
def sizeHint(self): # type: () -> QSize
# reimplemented
return self._get_size_hint()
def minimumSizeHint(self): # type: () -> QSize
# reimplemented
return self._get_size_hint()
# workaround for QTBUG-67583
def mousePressEvent(self, event): # type: (QMouseEvent) -> None
# reimplemented
self.__in_mousePressEvent = True
super().mousePressEvent(event)
self.__in_mousePressEvent = False
def showPopup(self): # type: () -> None
# reimplemented
super().showPopup()
if self.__in_mousePressEvent:
self.__yamrit.start(QApplication.doubleClickInterval())
def eventFilter(self, obj, event):
# type: (QObject, QEvent) -> bool
if event.type() == QEvent.MouseButtonRelease \
and event.button() == Qt.LeftButton \
and obj is self.view().viewport() \
and self.__yamrit.isActive():
return True
else:
return super().eventFilter(obj, event)
class _ComboBoxListDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
# type: (QPainter, QStyleOptionViewItem, QModelIndex) -> None
super().paint(painter, option, index)
if index.data(Qt.AccessibleDescriptionRole) == "separator":
palette = option.palette # type: QPalette
brush = palette.brush(QPalette.Disabled, QPalette.WindowText)
painter.setPen(QPen(brush, 1.0))
rect = option.rect # type: QRect
y = rect.center().y()
painter.drawLine(rect.left(), y, rect.left() + rect.width(), y)
class ComboBoxSearch(QComboBox):
"""
A drop down list combo box with filter/search.
The popup list view is filtered by text entered in the filter field.
Note
----
`popup`, `lineEdit` and `completer` from the base QComboBox class are
unused. Setting/modifying them will have no effect.
"""
# NOTE: Setting editable + QComboBox.NoInsert policy + ... did not achieve
# the same results.
def __init__(self, parent=None, **kwargs):
self.__maximumContentsLength = MAXIMUM_CONTENTS_LENGTH
self.__searchline = QLineEdit(visible=False, frame=False)
self.__searchline.setAttribute(Qt.WA_MacShowFocusRect, False)
self.__popup = None # type: Optional[QAbstractItemModel]
self.__proxy = None # type: Optional[QSortFilterProxyModel]
self.__popupTimer = QElapsedTimer()
super().__init__(parent, **kwargs)
self.__searchline.setParent(self)
self.__searchline.setFocusProxy(self)
self.setFocusPolicy(Qt.StrongFocus)
def setMaximumContentsLength(self, length): # type: (int) -> None
"""
Set the maximum contents length hint.
The hint specifies the upper bound on the `sizeHint` and
`minimumSizeHint` width specified in character length.
Set to 0 or negative value to disable.
Note
----
This property does not affect the widget's `maximumSize`.
The widget can still grow depending on its `sizePolicy`.
Parameters
----------
length : int
Maximum contents length hint.
"""
if self.__maximumContentsLength != length:
self.__maximumContentsLength = length
self.updateGeometry()
def _get_size_hint(self):
sh = super().sizeHint()
if self.__maximumContentsLength > 0:
width = (
self.fontMetrics().horizontalAdvance("X") * self.__maximumContentsLength
+ self.iconSize().width() + 4
)
sh = sh.boundedTo(QSize(width, sh.height()))
return sh
def sizeHint(self): # type: () -> QSize
# reimplemented
return self._get_size_hint()
def minimumSizeHint(self): # type: () -> QSize
# reimplemented
return self._get_size_hint()
def showPopup(self):
# type: () -> None
"""
Reimplemented from QComboBox.showPopup
Popup up a customized view and filter edit line.
Note
----
The .popup(), .lineEdit(), .completer() of the base class are not used.
"""
if self.__popup is not None:
# We have user entered state that cannot be disturbed
# (entered filter text, scroll offset, ...)
return # pragma: no cover
if self.count() == 0:
return
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
popup = QListView(
uniformItemSizes=True,
horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
verticalScrollBarPolicy=Qt.ScrollBarAsNeeded,
iconSize=self.iconSize(),
)
popup.setFocusProxy(self.__searchline)
popup.setParent(self, Qt.Popup | Qt.FramelessWindowHint)
popup.setItemDelegate(_ComboBoxListDelegate(popup))
proxy = QSortFilterProxyModel(
popup, filterCaseSensitivity=Qt.CaseInsensitive
)
proxy.setFilterKeyColumn(self.modelColumn())
proxy.setSourceModel(self.model())
popup.setModel(proxy)
root = proxy.mapFromSource(self.rootModelIndex())
popup.setRootIndex(root)
self.__popup = popup
self.__proxy = proxy
self.__searchline.setText("")
self.__searchline.setPlaceholderText("Filter...")
self.__searchline.setVisible(True)
self.__searchline.textEdited.connect(proxy.setFilterFixedString)
style = self.style() # type: QStyle
popuprect_origin = style.subControlRect(
QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxListBoxPopup, self
) # type: QRect
if sys.platform == "darwin":
slmargin = self.__searchline.style() \
.pixelMetric(QStyle.PM_FocusFrameVMargin)
popuprect_origin.adjust(slmargin // 2, 0,
-(slmargin * 3) // 2, slmargin)
popuprect_origin = QRect(
self.mapToGlobal(popuprect_origin.topLeft()),
popuprect_origin.size()
)
editrect = style.subControlRect(
QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self
) # type: QRect
self.__searchline.setGeometry(editrect)
screenrect = self.screen().availableGeometry()
# get the height for the view
listrect = QRect()
for i in range(min(proxy.rowCount(root), self.maxVisibleItems())):
index = proxy.index(i, self.modelColumn(), root)
if index.isValid():
listrect = listrect.united(popup.visualRect(index))
if listrect.height() >= screenrect.height():
break
window = popup.window() # type: QWidget
window.ensurePolished()
if window.layout() is not None:
window.layout().activate()
else:
QApplication.sendEvent(window, QEvent(QEvent.LayoutRequest))
margins = qwidget_margin_within(popup.viewport(), window)
height = (listrect.height() + 2 * popup.spacing() +
margins.top() + margins.bottom())
popup_size = (QSize(popuprect_origin.width(), height)
.expandedTo(window.minimumSize())
.boundedTo(window.maximumSize())
.boundedTo(screenrect.size()))
popuprect = dropdown_popup_geometry(
popup_size, popuprect_origin, screenrect)
popup.setGeometry(popuprect)
current = proxy.mapFromSource(
self.model().index(self.currentIndex(), self.modelColumn(),
self.rootModelIndex()))
popup.setCurrentIndex(current)
popup.scrollTo(current, QAbstractItemView.EnsureVisible)
popup.show()
popup.setFocus(Qt.PopupFocusReason)
popup.installEventFilter(self)
popup.viewport().installEventFilter(self)
popup.viewport().setMouseTracking(True)
self.update()
self.__popupTimer.restart()
def hidePopup(self):
"""Reimplemented"""
if self.__popup is not None:
popup = self.__popup
self.__popup = self.__proxy = None
popup.setFocusProxy(None)
popup.hide()
popup.deleteLater()
popup.removeEventFilter(self)
popup.viewport().removeEventFilter(self)
# need to call base hidePopup even though the base showPopup was not
# called (update internal state wrt. 'pressed' arrow, ...)
super().hidePopup()
self.__searchline.hide()
self.update()
def initStyleOption(self, option):
# type: (QStyleOptionComboBox) -> None
super().initStyleOption(option)
option.editable = True
def __updateGeometries(self):
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
editarea = self.style().subControlRect(
QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self)
self.__searchline.setGeometry(editarea)
def resizeEvent(self, event):
"""Reimplemented."""
super().resizeEvent(event)
self.__updateGeometries()
def paintEvent(self, event):
"""Reimplemented."""
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
painter = QStylePainter(self)
painter.drawComplexControl(QStyle.CC_ComboBox, opt)
if not self.__searchline.isVisibleTo(self):
opt.editable = False
painter.drawControl(QStyle.CE_ComboBoxLabel, opt)
def eventFilter(self, obj, event): # pylint: disable=too-many-branches
# type: (QObject, QEvent) -> bool
"""Reimplemented."""
etype = event.type()
if etype == QEvent.FocusOut and self.__popup is not None:
self.hidePopup()
return True
if etype == QEvent.Hide and self.__popup is not None:
self.hidePopup()
return False
if etype == QEvent.KeyPress or etype == QEvent.KeyRelease or \
etype == QEvent.ShortcutOverride and obj is self.__popup:
event = event # type: QKeyEvent
key, modifiers = event.key(), event.modifiers()
if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Select):
current = self.__popup.currentIndex()
if current.isValid():
self.__activateProxyIndex(current)
elif key in (Qt.Key_Up, Qt.Key_Down,
Qt.Key_PageUp, Qt.Key_PageDown):
return False #
elif key in (Qt.Key_Tab, Qt.Key_Backtab):
pass
elif key == Qt.Key_Escape or \
(key == Qt.Key_F4 and modifiers & Qt.AltModifier):
self.__popup.hide()
return True
else:
# pass the input events to the filter edit line (no propagation
# up the parent chain).
self.__searchline.event(event)
if event.isAccepted():
return True
if etype == QEvent.MouseButtonRelease and self.__popup is not None \
and obj is self.__popup.viewport() \
and self.__popupTimer.elapsed() >= \
QApplication.doubleClickInterval():
event = event # type: QMouseEvent
index = self.__popup.indexAt(event.pos())
if index.isValid():
self.__activateProxyIndex(index)
if etype == QEvent.MouseMove and self.__popup is not None \
and obj is self.__popup.viewport():
event = event # type: QMouseEvent
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
style = self.style() # type: QStyle
if style.styleHint(QStyle.SH_ComboBox_ListMouseTracking, opt, self):
index = self.__popup.indexAt(event.pos())
if index.isValid() and \
index.flags() & (Qt.ItemIsEnabled | Qt.ItemIsSelectable):
self.__popup.setCurrentIndex(index)
if etype == QEvent.MouseButtonPress and self.__popup is obj:
# Popup border or out of window mouse button press/release.
# At least on windows this needs to be handled.
style = self.style()
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
opt.subControls = QStyle.SC_All
opt.activeSubControls = QStyle.SC_ComboBoxArrow
pos = self.mapFromGlobal(event.globalPos())
sc = style.hitTestComplexControl(QStyle.CC_ComboBox, opt, pos, self)
if sc != QStyle.SC_None:
self.__popup.setAttribute(Qt.WA_NoMouseReplay)
self.hidePopup()
return super().eventFilter(obj, event)
def __activateProxyIndex(self, index):
# type: (QModelIndex) -> None
# Set current and activate the source index corresponding to the proxy
# index in the popup's model.
if self.__popup is not None and index.isValid():
proxy = self.__popup.model()
assert index.model() is proxy
index = proxy.mapToSource(index)
assert index.model() is self.model()
if index.isValid() and \
index.flags() & (Qt.ItemIsEnabled | Qt.ItemIsSelectable):
self.hidePopup()
self.setCurrentIndex(index.row())
qcombobox_emit_activated(self, index.row())
def qcombobox_emit_activated(cb: QComboBox, index: int):
cb.activated[int].emit(index)
text = cb.itemText(index)
if QT_VERSION >= 0x050f00: # 5.15
cb.textActivated.emit(text)
if QT_VERSION < 0x060000: # 6.0
cb.activated[str].emit(text)
def qwidget_margin_within(widget, ancestor):
# type: (QWidget, QWidget) -> QMargins
"""
Return the 'margins' of widget within its 'ancestor'
Ancestor must be within the widget's parent hierarchy and both widgets must
share the same top level window.
Parameters
----------
widget : QWidget
ancestor : QWidget
Returns
-------
margins: QMargins
"""
assert ancestor.isAncestorOf(widget)
assert ancestor.window() is widget.window()
r1 = widget.geometry()
r2 = ancestor.geometry()
topleft = r1.topLeft()
bottomright = r1.bottomRight()
topleft = widget.mapTo(ancestor, topleft)
bottomright = widget.mapTo(ancestor, bottomright)
return QMargins(topleft.x(), topleft.y(),
r2.right() - bottomright.x(),
r2.bottom() - bottomright.y())