GUIElements.py 8.0 KB

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