GUIElements.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. from PyQt4 import QtGui, QtCore
  2. from copy import copy
  3. #import FlatCAMApp
  4. import re
  5. import logging
  6. log = logging.getLogger('base')
  7. class RadioSet(QtGui.QWidget):
  8. def __init__(self, choices, orientation='horizontal', parent=None):
  9. """
  10. The choices are specified as a list of dictionaries containing:
  11. * 'label': Shown in the UI
  12. * 'value': The value returned is selected
  13. :param choices: List of choices. See description.
  14. :param orientation: 'horizontal' (default) of 'vertical'.
  15. :param parent: Qt parent widget.
  16. :type choices: list
  17. """
  18. super(RadioSet, self).__init__(parent)
  19. self.choices = copy(choices)
  20. if orientation == 'horizontal':
  21. layout = QtGui.QHBoxLayout()
  22. else:
  23. layout = QtGui.QVBoxLayout()
  24. group = QtGui.QButtonGroup(self)
  25. for choice in self.choices:
  26. choice['radio'] = QtGui.QRadioButton(choice['label'])
  27. group.addButton(choice['radio'])
  28. layout.addWidget(choice['radio'], stretch=0)
  29. choice['radio'].toggled.connect(self.on_toggle)
  30. layout.addStretch()
  31. self.setLayout(layout)
  32. self.group_toggle_fn = lambda: None
  33. def on_toggle(self):
  34. log.debug("Radio toggled")
  35. radio = self.sender()
  36. if radio.isChecked():
  37. self.group_toggle_fn()
  38. return
  39. def get_value(self):
  40. for choice in self.choices:
  41. if choice['radio'].isChecked():
  42. return choice['value']
  43. log.error("No button was toggled in RadioSet.")
  44. return None
  45. def set_value(self, val):
  46. for choice in self.choices:
  47. if choice['value'] == val:
  48. choice['radio'].setChecked(True)
  49. return
  50. log.error("Value given is not part of this RadioSet: %s" % str(val))
  51. class LengthEntry(QtGui.QLineEdit):
  52. def __init__(self, output_units='IN', parent=None):
  53. super(LengthEntry, self).__init__(parent)
  54. self.output_units = output_units
  55. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  56. # Unit conversion table OUTPUT-INPUT
  57. self.scales = {
  58. 'IN': {'IN': 1.0,
  59. 'MM': 1/25.4},
  60. 'MM': {'IN': 25.4,
  61. 'MM': 1.0}
  62. }
  63. self.readyToEdit = True
  64. def mousePressEvent(self, e, Parent=None):
  65. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  66. if self.readyToEdit:
  67. self.selectAll()
  68. self.readyToEdit = False
  69. def focusOutEvent(self, e):
  70. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  71. self.deselect()
  72. self.readyToEdit = True
  73. def returnPressed(self, *args, **kwargs):
  74. val = self.get_value()
  75. if val is not None:
  76. self.set_text(str(val))
  77. else:
  78. log.warning("Could not interpret entry: %s" % self.get_text())
  79. def get_value(self):
  80. raw = str(self.text()).strip(' ')
  81. # match = self.format_re.search(raw)
  82. try:
  83. units = raw[-2:]
  84. units = self.scales[self.output_units][units.upper()]
  85. value = raw[:-2]
  86. return float(eval(value))*units
  87. except IndexError:
  88. value = raw
  89. return float(eval(value))
  90. except KeyError:
  91. value = raw
  92. return float(eval(value))
  93. except:
  94. log.warning("Could not parse value in entry: %s" % str(raw))
  95. return None
  96. def set_value(self, val):
  97. self.setText(str(val))
  98. class FloatEntry(QtGui.QLineEdit):
  99. def __init__(self, parent=None):
  100. super(FloatEntry, self).__init__(parent)
  101. self.readyToEdit = True
  102. def mousePressEvent(self, e, Parent=None):
  103. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  104. if self.readyToEdit:
  105. self.selectAll()
  106. self.readyToEdit = False
  107. def focusOutEvent(self, e):
  108. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  109. self.deselect()
  110. self.readyToEdit = True
  111. def returnPressed(self, *args, **kwargs):
  112. val = self.get_value()
  113. if val is not None:
  114. self.set_text(str(val))
  115. else:
  116. log.warning("Could not interpret entry: %s" % self.text())
  117. def get_value(self):
  118. raw = str(self.text()).strip(' ')
  119. try:
  120. evaled = eval(raw)
  121. except:
  122. log.error("Could not evaluate: %s" % str(raw))
  123. return None
  124. return float(evaled)
  125. def set_value(self, val):
  126. self.setText("%.6f" % val)
  127. class IntEntry(QtGui.QLineEdit):
  128. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  129. super(IntEntry, self).__init__(parent)
  130. self.allow_empty = allow_empty
  131. self.empty_val = empty_val
  132. self.readyToEdit = True
  133. def mousePressEvent(self, e, Parent=None):
  134. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  135. if self.readyToEdit:
  136. self.selectAll()
  137. self.readyToEdit = False
  138. def focusOutEvent(self, e):
  139. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  140. self.deselect()
  141. self.readyToEdit = True
  142. def get_value(self):
  143. if self.allow_empty:
  144. if str(self.text()) == "":
  145. return self.empty_val
  146. return int(self.text())
  147. def set_value(self, val):
  148. if val == self.empty_val and self.allow_empty:
  149. self.setText("")
  150. return
  151. self.setText(str(val))
  152. class FCEntry(QtGui.QLineEdit):
  153. def __init__(self, parent=None):
  154. super(FCEntry, self).__init__(parent)
  155. self.readyToEdit = True
  156. def mousePressEvent(self, e, Parent=None):
  157. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  158. if self.readyToEdit:
  159. self.selectAll()
  160. self.readyToEdit = False
  161. def focusOutEvent(self, e):
  162. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  163. self.deselect()
  164. self.readyToEdit = True
  165. def get_value(self):
  166. return str(self.text())
  167. def set_value(self, val):
  168. self.setText(str(val))
  169. class EvalEntry(QtGui.QLineEdit):
  170. def __init__(self, parent=None):
  171. super(EvalEntry, self).__init__(parent)
  172. self.readyToEdit = True
  173. def mousePressEvent(self, e, Parent=None):
  174. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  175. if self.readyToEdit:
  176. self.selectAll()
  177. self.readyToEdit = False
  178. def focusOutEvent(self, e):
  179. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  180. self.deselect()
  181. self.readyToEdit = True
  182. def returnPressed(self, *args, **kwargs):
  183. val = self.get_value()
  184. if val is not None:
  185. self.setText(str(val))
  186. else:
  187. log.warning("Could not interpret entry: %s" % self.get_text())
  188. def get_value(self):
  189. raw = str(self.text()).strip(' ')
  190. try:
  191. return eval(raw)
  192. except:
  193. log.error("Could not evaluate: %s" % str(raw))
  194. return None
  195. def set_value(self, val):
  196. self.setText(str(val))
  197. class FCCheckBox(QtGui.QCheckBox):
  198. def __init__(self, label='', parent=None):
  199. super(FCCheckBox, self).__init__(str(label), parent)
  200. def get_value(self):
  201. return self.isChecked()
  202. def set_value(self, val):
  203. self.setChecked(val)
  204. def toggle(self):
  205. self.set_value(not self.get_value())
  206. class FCTextArea(QtGui.QPlainTextEdit):
  207. def __init__(self, parent=None):
  208. super(FCTextArea, self).__init__(parent)
  209. def set_value(self, val):
  210. self.setPlainText(val)
  211. def get_value(self):
  212. return str(self.toPlainText())
  213. class VerticalScrollArea(QtGui.QScrollArea):
  214. """
  215. This widget extends QtGui.QScrollArea to make a vertical-only
  216. scroll area that also expands horizontally to accomodate
  217. its contents.
  218. """
  219. def __init__(self, parent=None):
  220. QtGui.QScrollArea.__init__(self, parent=parent)
  221. self.setWidgetResizable(True)
  222. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  223. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  224. def eventFilter(self, source, event):
  225. """
  226. The event filter gets automatically installed when setWidget()
  227. is called.
  228. :param source:
  229. :param event:
  230. :return:
  231. """
  232. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  233. # log.debug("VerticalScrollArea: Widget resized:")
  234. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  235. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  236. self.setMinimumWidth(self.widget().sizeHint().width() +
  237. self.verticalScrollBar().sizeHint().width())
  238. # if self.verticalScrollBar().isVisible():
  239. # log.debug(" Scroll bar visible")
  240. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  241. # self.verticalScrollBar().width())
  242. # else:
  243. # log.debug(" Scroll bar hidden")
  244. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  245. return QtGui.QWidget.eventFilter(self, source, event)
  246. class OptionalInputSection:
  247. def __init__(self, cb, optinputs):
  248. """
  249. Associates the a checkbox with a set of inputs.
  250. :param cb: Checkbox that enables the optional inputs.
  251. :param optinputs: List of widgets that are optional.
  252. :return:
  253. """
  254. assert isinstance(cb, FCCheckBox), \
  255. "Expected an FCCheckBox, got %s" % type(cb)
  256. self.cb = cb
  257. self.optinputs = optinputs
  258. self.on_cb_change()
  259. self.cb.stateChanged.connect(self.on_cb_change)
  260. def on_cb_change(self):
  261. if self.cb.checkState():
  262. for widget in self.optinputs:
  263. widget.setEnabled(True)
  264. else:
  265. for widget in self.optinputs:
  266. widget.setEnabled(False)