GUIElements.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. def returnPressed(self, *args, **kwargs):
  64. val = self.get_value()
  65. if val is not None:
  66. self.set_text(str(val))
  67. else:
  68. log.warning("Could not interpret entry: %s" % self.get_text())
  69. def get_value(self):
  70. raw = str(self.text()).strip(' ')
  71. # match = self.format_re.search(raw)
  72. try:
  73. units = raw[-2:]
  74. units = self.scales[self.output_units][units.upper()]
  75. value = raw[:-2]
  76. return float(eval(value))*units
  77. except IndexError:
  78. value = raw
  79. return float(eval(value))
  80. except KeyError:
  81. value = raw
  82. return float(eval(value))
  83. except:
  84. log.warning("Could not parse value in entry: %s" % str(raw))
  85. return None
  86. def set_value(self, val):
  87. self.setText(str(val))
  88. class FloatEntry(QtGui.QLineEdit):
  89. def __init__(self, parent=None):
  90. super(FloatEntry, self).__init__(parent)
  91. def returnPressed(self, *args, **kwargs):
  92. val = self.get_value()
  93. if val is not None:
  94. self.set_text(str(val))
  95. else:
  96. log.warning("Could not interpret entry: %s" % self.text())
  97. def get_value(self):
  98. raw = str(self.text()).strip(' ')
  99. try:
  100. evaled = eval(raw)
  101. except:
  102. log.error("Could not evaluate: %s" % str(raw))
  103. return None
  104. return float(evaled)
  105. def set_value(self, val):
  106. self.setText("%.6f" % val)
  107. class IntEntry(QtGui.QLineEdit):
  108. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  109. super(IntEntry, self).__init__(parent)
  110. self.allow_empty = allow_empty
  111. self.empty_val = empty_val
  112. def get_value(self):
  113. if self.allow_empty:
  114. if str(self.text()) == "":
  115. return self.empty_val
  116. return int(self.text())
  117. def set_value(self, val):
  118. if val == self.empty_val and self.allow_empty:
  119. self.setText("")
  120. return
  121. self.setText(str(val))
  122. class FCEntry(QtGui.QLineEdit):
  123. def __init__(self, parent=None):
  124. super(FCEntry, self).__init__(parent)
  125. def get_value(self):
  126. return str(self.text())
  127. def set_value(self, val):
  128. self.setText(str(val))
  129. class EvalEntry(QtGui.QLineEdit):
  130. def __init__(self, parent=None):
  131. super(EvalEntry, self).__init__(parent)
  132. def returnPressed(self, *args, **kwargs):
  133. val = self.get_value()
  134. if val is not None:
  135. self.setText(str(val))
  136. else:
  137. log.warning("Could not interpret entry: %s" % self.get_text())
  138. def get_value(self):
  139. raw = str(self.text()).strip(' ')
  140. try:
  141. return eval(raw)
  142. except:
  143. log.error("Could not evaluate: %s" % str(raw))
  144. return None
  145. def set_value(self, val):
  146. self.setText(str(val))
  147. class FCCheckBox(QtGui.QCheckBox):
  148. def __init__(self, label='', parent=None):
  149. super(FCCheckBox, self).__init__(str(label), parent)
  150. def get_value(self):
  151. return self.isChecked()
  152. def set_value(self, val):
  153. self.setChecked(val)
  154. def toggle(self):
  155. self.set_value(not self.get_value())
  156. class FCTextArea(QtGui.QPlainTextEdit):
  157. def __init__(self, parent=None):
  158. super(FCTextArea, self).__init__(parent)
  159. def set_value(self, val):
  160. self.setPlainText(val)
  161. def get_value(self):
  162. return str(self.toPlainText())
  163. class VerticalScrollArea(QtGui.QScrollArea):
  164. """
  165. This widget extends QtGui.QScrollArea to make a vertical-only
  166. scroll area that also expands horizontally to accomodate
  167. its contents.
  168. """
  169. def __init__(self, parent=None):
  170. QtGui.QScrollArea.__init__(self, parent=parent)
  171. self.setWidgetResizable(True)
  172. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  173. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  174. def eventFilter(self, source, event):
  175. """
  176. The event filter gets automatically installed when setWidget()
  177. is called.
  178. :param source:
  179. :param event:
  180. :return:
  181. """
  182. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  183. # log.debug("VerticalScrollArea: Widget resized:")
  184. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  185. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  186. self.setMinimumWidth(self.widget().sizeHint().width() +
  187. self.verticalScrollBar().sizeHint().width())
  188. # if self.verticalScrollBar().isVisible():
  189. # log.debug(" Scroll bar visible")
  190. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  191. # self.verticalScrollBar().width())
  192. # else:
  193. # log.debug(" Scroll bar hidden")
  194. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  195. return QtGui.QWidget.eventFilter(self, source, event)
  196. class OptionalInputSection:
  197. def __init__(self, cb, optinputs):
  198. """
  199. Associates the a checkbox with a set of inputs.
  200. :param cb: Checkbox that enables the optional inputs.
  201. :param optinputs: List of widgets that are optional.
  202. :return:
  203. """
  204. assert isinstance(cb, FCCheckBox), \
  205. "Expected an FCCheckBox, got %s" % type(cb)
  206. self.cb = cb
  207. self.optinputs = optinputs
  208. self.on_cb_change()
  209. self.cb.stateChanged.connect(self.on_cb_change)
  210. def on_cb_change(self):
  211. if self.cb.checkState():
  212. for widget in self.optinputs:
  213. widget.setEnabled(True)
  214. else:
  215. for widget in self.optinputs:
  216. widget.setEnabled(False)