GUIElements.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. :type choices: list
  15. """
  16. super(RadioSet, self).__init__(parent)
  17. self.choices = copy(choices)
  18. if orientation == 'horizontal':
  19. layout = QtGui.QHBoxLayout()
  20. else:
  21. layout = QtGui.QVBoxLayout()
  22. group = QtGui.QButtonGroup(self)
  23. for choice in self.choices:
  24. choice['radio'] = QtGui.QRadioButton(choice['label'])
  25. group.addButton(choice['radio'])
  26. layout.addWidget(choice['radio'], stretch=0)
  27. choice['radio'].toggled.connect(self.on_toggle)
  28. layout.addStretch()
  29. self.setLayout(layout)
  30. self.group_toggle_fn = lambda: None
  31. def on_toggle(self):
  32. log.debug("Radio toggled")
  33. radio = self.sender()
  34. if radio.isChecked():
  35. self.group_toggle_fn()
  36. return
  37. def get_value(self):
  38. for choice in self.choices:
  39. if choice['radio'].isChecked():
  40. return choice['value']
  41. log.error("No button was toggled in RadioSet.")
  42. return None
  43. def set_value(self, val):
  44. for choice in self.choices:
  45. if choice['value'] == val:
  46. choice['radio'].setChecked(True)
  47. return
  48. log.error("Value given is not part of this RadioSet: %s" % str(val))
  49. class LengthEntry(QtGui.QLineEdit):
  50. def __init__(self, output_units='IN', parent=None):
  51. super(LengthEntry, self).__init__(parent)
  52. self.output_units = output_units
  53. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  54. # Unit conversion table OUTPUT-INPUT
  55. self.scales = {
  56. 'IN': {'IN': 1.0,
  57. 'MM': 1/25.4},
  58. 'MM': {'IN': 25.4,
  59. 'MM': 1.0}
  60. }
  61. def returnPressed(self, *args, **kwargs):
  62. val = self.get_value()
  63. if val is not None:
  64. self.set_text(QtCore.QString(str(val)))
  65. else:
  66. log.warning("Could not interpret entry: %s" % self.get_text())
  67. def get_value(self):
  68. raw = str(self.text()).strip(' ')
  69. match = self.format_re.search(raw)
  70. if not match:
  71. return None
  72. try:
  73. if match.group(2) is not None and match.group(2).upper() in self.scales:
  74. return float(eval(match.group(1)))*float(self.scales[self.output_units][match.group(2).upper()])
  75. else:
  76. return float(eval(match.group(1)))
  77. except:
  78. log.warning("Could not parse value in entry: %s" % str(raw))
  79. return None
  80. def set_value(self, val):
  81. self.setText(QtCore.QString(str(val)))
  82. class FloatEntry(QtGui.QLineEdit):
  83. def __init__(self, parent=None):
  84. super(FloatEntry, self).__init__(parent)
  85. def returnPressed(self, *args, **kwargs):
  86. val = self.get_value()
  87. if val is not None:
  88. self.set_text(QtCore.QString(str(val)))
  89. else:
  90. log.warning("Could not interpret entry: %s" % self.text())
  91. def get_value(self):
  92. raw = str(self.text()).strip(' ')
  93. try:
  94. evaled = eval(raw)
  95. except:
  96. log.error("Could not evaluate: %s" % str(raw))
  97. return None
  98. return float(evaled)
  99. def set_value(self, val):
  100. self.setText("%.6f" % val)
  101. class IntEntry(QtGui.QLineEdit):
  102. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  103. super(IntEntry, self).__init__(parent)
  104. self.allow_empty = allow_empty
  105. self.empty_val = empty_val
  106. def get_value(self):
  107. if self.allow_empty:
  108. if str(self.text()) == "":
  109. return self.empty_val
  110. return int(self.text())
  111. def set_value(self, val):
  112. if val == self.empty_val and self.allow_empty:
  113. self.setText(QtCore.QString(""))
  114. return
  115. self.setText(QtCore.QString(str(val)))
  116. class FCEntry(QtGui.QLineEdit):
  117. def __init__(self, parent=None):
  118. super(FCEntry, self).__init__(parent)
  119. def get_value(self):
  120. return str(self.text())
  121. def set_value(self, val):
  122. self.setText(QtCore.QString(str(val)))
  123. class EvalEntry(QtGui.QLineEdit):
  124. def __init__(self, parent=None):
  125. super(EvalEntry, self).__init__(parent)
  126. def returnPressed(self, *args, **kwargs):
  127. val = self.get_value()
  128. if val is not None:
  129. self.setText(QtCore.QString(str(val)))
  130. else:
  131. log.warning("Could not interpret entry: %s" % self.get_text())
  132. def get_value(self):
  133. raw = str(self.text()).strip(' ')
  134. try:
  135. return eval(raw)
  136. except:
  137. log.error("Could not evaluate: %s" % str(raw))
  138. return None
  139. def set_value(self, val):
  140. self.setText(QtCore.QString(str(val)))
  141. class FCCheckBox(QtGui.QCheckBox):
  142. def __init__(self, label='', parent=None):
  143. super(FCCheckBox, self).__init__(QtCore.QString(label), parent)
  144. def get_value(self):
  145. return self.isChecked()
  146. def set_value(self, val):
  147. self.setChecked(val)
  148. class FCTextArea(QtGui.QPlainTextEdit):
  149. def __init__(self, parent=None):
  150. super(FCTextArea, self).__init__(parent)
  151. def set_value(self, val):
  152. self.setPlainText(val)
  153. def get_value(self):
  154. return str(self.toPlainText())
  155. class VerticalScrollArea(QtGui.QScrollArea):
  156. """
  157. This widget extends QtGui.QScrollArea to make a vertical-only
  158. scroll area that also expands horizontally to accomodate
  159. its contents.
  160. """
  161. def __init__(self, parent=None):
  162. QtGui.QScrollArea.__init__(self, parent=parent)
  163. self.setWidgetResizable(True)
  164. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  165. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  166. def eventFilter(self, source, event):
  167. """
  168. The event filter gets automatically installed when setWidget()
  169. is called.
  170. :param source:
  171. :param event:
  172. :return:
  173. """
  174. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  175. # log.debug("VerticalScrollArea: Widget resized:")
  176. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  177. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  178. self.setMinimumWidth(self.widget().sizeHint().width() +
  179. self.verticalScrollBar().sizeHint().width())
  180. # if self.verticalScrollBar().isVisible():
  181. # log.debug(" Scroll bar visible")
  182. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  183. # self.verticalScrollBar().width())
  184. # else:
  185. # log.debug(" Scroll bar hidden")
  186. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  187. return QtGui.QWidget.eventFilter(self, source, event)
  188. class OptionalInputSection():
  189. def __init__(self, cb, optinputs):
  190. assert isinstance(cb, FCCheckBox)
  191. self.cb = cb
  192. self.optinputs = optinputs
  193. self.on_cb_change()
  194. self.cb.stateChanged.connect(self.on_cb_change)
  195. def on_cb_change(self):
  196. if self.cb.checkState():
  197. for widget in self.optinputs:
  198. widget.setEnabled(True)
  199. else:
  200. for widget in self.optinputs:
  201. widget.setEnabled(False)