| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
from PyQt5 import QtCore, QtGui, QtWidgets |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
MIN_TAB_WIDTH = 1 |
| 25 |
MAX_TAB_WIDTH = 12 |
| 26 |
|
| 27 |
class TabWidthMenuSelector(QtWidgets.QMenu): |
| 28 |
"""Menu to control tab width.""" |
| 29 |
def __init__(self, initial_tab_width=None, label_text=None, onChanged=None, *args): |
| 30 |
"""Create tab width menu. |
| 31 |
@param label_text: text for label. |
| 32 |
@param onChanged: callback to processing tab width change. |
| 33 |
""" |
| 34 |
QtWidgets.QMenu.__init__(self, *args) |
| 35 |
self.onChanged = onChanged |
| 36 |
if onChanged is None: |
| 37 |
self.onChanged = lambda settabwidth: None |
| 38 |
|
| 39 |
self.setTitle(label_text) |
| 40 |
|
| 41 |
self.action_group = QtWidgets.QActionGroup(self) |
| 42 |
|
| 43 |
self.tabwidth_actions = {} |
| 44 |
for tabwidth in range(MIN_TAB_WIDTH, MAX_TAB_WIDTH+1): |
| 45 |
action = QtWidgets.QAction(str(tabwidth), self.action_group) |
| 46 |
action.setCheckable(True) |
| 47 |
action.setData(tabwidth) |
| 48 |
self.addAction(action) |
| 49 |
self.tabwidth_actions[tabwidth] = action |
| 50 |
|
| 51 |
self._tabwidth = None |
| 52 |
self._has_separator = False |
| 53 |
|
| 54 |
self.triggered[QtWidgets.QAction].connect(self._triggered) |
| 55 |
|
| 56 |
if initial_tab_width is not None: |
| 57 |
self.setTabWidth(initial_tab_width) |
| 58 |
self._triggered(self.tabwidth_actions[initial_tab_width]) |
| 59 |
|
| 60 |
def _triggered(self, action): |
| 61 |
tw = action.data() |
| 62 |
if tw != self._tabwidth: |
| 63 |
self._tabwidth = tw |
| 64 |
self.onChanged(tw) |
| 65 |
|
| 66 |
def setTabWidth(self, width): |
| 67 |
if width not in self.tabwidth_actions: |
| 68 |
action = QtWidgets.QAction(str(width), self.action_group) |
| 69 |
action.setCheckable(True) |
| 70 |
action.setData(width) |
| 71 |
|
| 72 |
for tw in sorted(self.tabwidth_actions.keys()): |
| 73 |
if tw > width: |
| 74 |
self.insertAction(action, self.tabwidth_actions[tw]) |
| 75 |
break |
| 76 |
else: |
| 77 |
|
| 78 |
if not self._has_separator: |
| 79 |
self.addSeparator() |
| 80 |
self._has_separator = True |
| 81 |
self.addAction(action) |
| 82 |
|
| 83 |
self.tabwidth_actions[width] = action |
| 84 |
|
| 85 |
self.tabwidth_actions[width].setChecked(True) |