GUIElements.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import pyqtSignal, pyqtSlot
  3. from copy import copy
  4. import re
  5. import logging
  6. log = logging.getLogger('base')
  7. EDIT_SIZE_HINT = 70
  8. class RadioSet(QtWidgets.QWidget):
  9. activated_custom = QtCore.pyqtSignal()
  10. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  11. """
  12. The choices are specified as a list of dictionaries containing:
  13. * 'label': Shown in the UI
  14. * 'value': The value returned is selected
  15. :param choices: List of choices. See description.
  16. :param orientation: 'horizontal' (default) of 'vertical'.
  17. :param parent: Qt parent widget.
  18. :type choices: list
  19. """
  20. super(RadioSet, self).__init__(parent)
  21. self.choices = copy(choices)
  22. if orientation == 'horizontal':
  23. layout = QtWidgets.QHBoxLayout()
  24. else:
  25. layout = QtWidgets.QVBoxLayout()
  26. group = QtWidgets.QButtonGroup(self)
  27. for choice in self.choices:
  28. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  29. group.addButton(choice['radio'])
  30. layout.addWidget(choice['radio'], stretch=0)
  31. choice['radio'].toggled.connect(self.on_toggle)
  32. layout.setContentsMargins(0, 0, 0, 0)
  33. if stretch is False:
  34. pass
  35. else:
  36. layout.addStretch()
  37. self.setLayout(layout)
  38. self.group_toggle_fn = lambda: None
  39. def on_toggle(self):
  40. # log.debug("Radio toggled")
  41. radio = self.sender()
  42. if radio.isChecked():
  43. self.group_toggle_fn()
  44. self.activated_custom.emit()
  45. return
  46. def get_value(self):
  47. for choice in self.choices:
  48. if choice['radio'].isChecked():
  49. return choice['value']
  50. log.error("No button was toggled in RadioSet.")
  51. return None
  52. def set_value(self, val):
  53. for choice in self.choices:
  54. if choice['value'] == val:
  55. choice['radio'].setChecked(True)
  56. return
  57. log.error("Value given is not part of this RadioSet: %s" % str(val))
  58. # class RadioGroupChoice(QtWidgets.QWidget):
  59. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  60. # """
  61. # The choices are specified as a list of dictionaries containing:
  62. #
  63. # * 'label': Shown in the UI
  64. # * 'value': The value returned is selected
  65. #
  66. # :param choices: List of choices. See description.
  67. # :param orientation: 'horizontal' (default) of 'vertical'.
  68. # :param parent: Qt parent widget.
  69. # :type choices: list
  70. # """
  71. # super().__init__(parent)
  72. #
  73. # group = QtGui.QButtonGroup(self)
  74. #
  75. # self.lbl1 = label_1
  76. # self.lbl2 = label_2
  77. # self.hide_list = hide_list
  78. # self.show_list = show_list
  79. #
  80. # self.btn1 = QtGui.QRadioButton(str(label_1))
  81. # self.btn2 = QtGui.QRadioButton(str(label_2))
  82. # group.addButton(self.btn1)
  83. # group.addButton(self.btn2)
  84. #
  85. # if to_check == 1:
  86. # self.btn1.setChecked(True)
  87. # else:
  88. # self.btn2.setChecked(True)
  89. #
  90. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  91. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  92. #
  93. # def btn_state(self, btn):
  94. # if btn.text() == self.lbl1:
  95. # if btn.isChecked() is True:
  96. # self.show_widgets(self.show_list)
  97. # self.hide_widgets(self.hide_list)
  98. # else:
  99. # self.show_widgets(self.hide_list)
  100. # self.hide_widgets(self.show_list)
  101. #
  102. # def hide_widgets(self, lst):
  103. # for wgt in lst:
  104. # wgt.hide()
  105. #
  106. # def show_widgets(self, lst):
  107. # for wgt in lst:
  108. # wgt.show()
  109. class LengthEntry(QtWidgets.QLineEdit):
  110. def __init__(self, output_units='IN', parent=None):
  111. super(LengthEntry, self).__init__(parent)
  112. self.output_units = output_units
  113. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  114. # Unit conversion table OUTPUT-INPUT
  115. self.scales = {
  116. 'IN': {'IN': 1.0,
  117. 'MM': 1/25.4},
  118. 'MM': {'IN': 25.4,
  119. 'MM': 1.0}
  120. }
  121. self.readyToEdit = True
  122. def mousePressEvent(self, e, Parent=None):
  123. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  124. if self.readyToEdit:
  125. self.selectAll()
  126. self.readyToEdit = False
  127. def focusOutEvent(self, e):
  128. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  129. self.deselect()
  130. self.readyToEdit = True
  131. def returnPressed(self, *args, **kwargs):
  132. val = self.get_value()
  133. if val is not None:
  134. self.set_text(str(val))
  135. else:
  136. log.warning("Could not interpret entry: %s" % self.get_text())
  137. def get_value(self):
  138. raw = str(self.text()).strip(' ')
  139. # match = self.format_re.search(raw)
  140. try:
  141. units = raw[-2:]
  142. units = self.scales[self.output_units][units.upper()]
  143. value = raw[:-2]
  144. return float(eval(value))*units
  145. except IndexError:
  146. value = raw
  147. return float(eval(value))
  148. except KeyError:
  149. value = raw
  150. return float(eval(value))
  151. except:
  152. log.warning("Could not parse value in entry: %s" % str(raw))
  153. return None
  154. def set_value(self, val):
  155. self.setText(str('%.4f' % val))
  156. def sizeHint(self):
  157. default_hint_size = super(LengthEntry, self).sizeHint()
  158. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  159. class FloatEntry(QtWidgets.QLineEdit):
  160. def __init__(self, parent=None):
  161. super(FloatEntry, self).__init__(parent)
  162. self.readyToEdit = True
  163. def mousePressEvent(self, e, Parent=None):
  164. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  165. if self.readyToEdit:
  166. self.selectAll()
  167. self.readyToEdit = False
  168. def focusOutEvent(self, e):
  169. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  170. self.deselect()
  171. self.readyToEdit = True
  172. def returnPressed(self, *args, **kwargs):
  173. val = self.get_value()
  174. if val is not None:
  175. self.set_text(str(val))
  176. else:
  177. log.warning("Could not interpret entry: %s" % self.text())
  178. def get_value(self):
  179. raw = str(self.text()).strip(' ')
  180. evaled = 0.0
  181. try:
  182. evaled = eval(raw)
  183. except:
  184. if evaled is not None:
  185. log.error("Could not evaluate: %s" % str(raw))
  186. return None
  187. return float(evaled)
  188. def set_value(self, val):
  189. if val is not None:
  190. self.setText("%.6f" % val)
  191. else:
  192. self.setText("")
  193. def sizeHint(self):
  194. default_hint_size = super(FloatEntry, self).sizeHint()
  195. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  196. class FloatEntry2(QtWidgets.QLineEdit):
  197. def __init__(self, parent=None):
  198. super(FloatEntry2, self).__init__(parent)
  199. self.readyToEdit = True
  200. def mousePressEvent(self, e, Parent=None):
  201. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  202. if self.readyToEdit:
  203. self.selectAll()
  204. self.readyToEdit = False
  205. def focusOutEvent(self, e):
  206. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  207. self.deselect()
  208. self.readyToEdit = True
  209. def get_value(self):
  210. raw = str(self.text()).strip(' ')
  211. evaled = 0.0
  212. try:
  213. evaled = eval(raw)
  214. except:
  215. if evaled is not None:
  216. log.error("Could not evaluate: %s" % str(raw))
  217. return None
  218. return float(evaled)
  219. def set_value(self, val):
  220. self.setText("%.6f" % val)
  221. def sizeHint(self):
  222. default_hint_size = super(FloatEntry2, self).sizeHint()
  223. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  224. class IntEntry(QtWidgets.QLineEdit):
  225. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  226. super(IntEntry, self).__init__(parent)
  227. self.allow_empty = allow_empty
  228. self.empty_val = empty_val
  229. self.readyToEdit = True
  230. def mousePressEvent(self, e, Parent=None):
  231. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  232. if self.readyToEdit:
  233. self.selectAll()
  234. self.readyToEdit = False
  235. def focusOutEvent(self, e):
  236. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  237. self.deselect()
  238. self.readyToEdit = True
  239. def get_value(self):
  240. if self.allow_empty:
  241. if str(self.text()) == "":
  242. return self.empty_val
  243. # make the text() first a float and then int because if text is a float type,
  244. # the int() can't convert directly a "text float" into a int type.
  245. ret_val = float(self.text())
  246. ret_val = int(ret_val)
  247. return ret_val
  248. def set_value(self, val):
  249. if val == self.empty_val and self.allow_empty:
  250. self.setText("")
  251. return
  252. self.setText(str(val))
  253. def sizeHint(self):
  254. default_hint_size = super(IntEntry, self).sizeHint()
  255. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  256. class FCEntry(QtWidgets.QLineEdit):
  257. def __init__(self, parent=None):
  258. super(FCEntry, self).__init__(parent)
  259. self.readyToEdit = True
  260. def mousePressEvent(self, e, Parent=None):
  261. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  262. if self.readyToEdit:
  263. self.selectAll()
  264. self.readyToEdit = False
  265. def focusOutEvent(self, e):
  266. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  267. self.deselect()
  268. self.readyToEdit = True
  269. def get_value(self):
  270. return str(self.text())
  271. def set_value(self, val):
  272. self.setText(str(val))
  273. def sizeHint(self):
  274. default_hint_size = super(FCEntry, self).sizeHint()
  275. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  276. class FCEntry2(FCEntry):
  277. def __init__(self, parent=None):
  278. super(FCEntry2, self).__init__(parent)
  279. self.readyToEdit = True
  280. def set_value(self, val):
  281. self.setText('%.5f' % float(val))
  282. class EvalEntry(QtWidgets.QLineEdit):
  283. def __init__(self, parent=None):
  284. super(EvalEntry, self).__init__(parent)
  285. self.readyToEdit = True
  286. def mousePressEvent(self, e, Parent=None):
  287. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  288. if self.readyToEdit:
  289. self.selectAll()
  290. self.readyToEdit = False
  291. def focusOutEvent(self, e):
  292. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  293. self.deselect()
  294. self.readyToEdit = True
  295. def returnPressed(self, *args, **kwargs):
  296. val = self.get_value()
  297. if val is not None:
  298. self.setText(str(val))
  299. else:
  300. log.warning("Could not interpret entry: %s" % self.get_text())
  301. def get_value(self):
  302. raw = str(self.text()).strip(' ')
  303. evaled = 0.0
  304. try:
  305. evaled = eval(raw)
  306. except:
  307. if evaled is not None:
  308. log.error("Could not evaluate: %s" % str(raw))
  309. return None
  310. return evaled
  311. def set_value(self, val):
  312. self.setText(str(val))
  313. def sizeHint(self):
  314. default_hint_size = super(EvalEntry, self).sizeHint()
  315. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  316. class EvalEntry2(QtWidgets.QLineEdit):
  317. def __init__(self, parent=None):
  318. super(EvalEntry2, self).__init__(parent)
  319. self.readyToEdit = True
  320. def mousePressEvent(self, e, Parent=None):
  321. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  322. if self.readyToEdit:
  323. self.selectAll()
  324. self.readyToEdit = False
  325. def focusOutEvent(self, e):
  326. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  327. self.deselect()
  328. self.readyToEdit = True
  329. def get_value(self):
  330. raw = str(self.text()).strip(' ')
  331. evaled = 0.0
  332. try:
  333. evaled = eval(raw)
  334. except:
  335. if evaled is not None:
  336. log.error("Could not evaluate: %s" % str(raw))
  337. return None
  338. return evaled
  339. def set_value(self, val):
  340. self.setText(str(val))
  341. def sizeHint(self):
  342. default_hint_size = super(EvalEntry2, self).sizeHint()
  343. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  344. class FCCheckBox(QtWidgets.QCheckBox):
  345. def __init__(self, label='', parent=None):
  346. super(FCCheckBox, self).__init__(str(label), parent)
  347. def get_value(self):
  348. return self.isChecked()
  349. def set_value(self, val):
  350. self.setChecked(val)
  351. def toggle(self):
  352. self.set_value(not self.get_value())
  353. class FCTextArea(QtWidgets.QPlainTextEdit):
  354. def __init__(self, parent=None):
  355. super(FCTextArea, self).__init__(parent)
  356. def set_value(self, val):
  357. self.setPlainText(val)
  358. def get_value(self):
  359. return str(self.toPlainText())
  360. def sizeHint(self):
  361. default_hint_size = super(FCTextArea, self).sizeHint()
  362. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  363. class FCTextAreaRich(QtWidgets.QTextEdit):
  364. def __init__(self, parent=None):
  365. super(FCTextAreaRich, self).__init__(parent)
  366. def set_value(self, val):
  367. self.setText(val)
  368. def get_value(self):
  369. return str(self.toPlainText())
  370. def sizeHint(self):
  371. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  372. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  373. class FCComboBox(QtWidgets.QComboBox):
  374. def __init__(self, parent=None):
  375. super(FCComboBox, self).__init__(parent)
  376. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  377. def wheelEvent(self, *args, **kwargs):
  378. pass
  379. def get_value(self):
  380. return str(self.currentText())
  381. def set_value(self, val):
  382. self.setCurrentIndex(self.findText(str(val)))
  383. class FCInputDialog(QtWidgets.QInputDialog):
  384. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None):
  385. super(FCInputDialog, self).__init__(parent)
  386. self.allow_empty = ok
  387. self.empty_val = val
  388. if title is None:
  389. self.title = 'title'
  390. else:
  391. self.title = title
  392. if text is None:
  393. self.text = 'text'
  394. else:
  395. self.text = text
  396. if min is None:
  397. self.min = 0
  398. else:
  399. self.min = min
  400. if max is None:
  401. self.max = 0
  402. else:
  403. self.max = max
  404. if decimals is None:
  405. self.decimals = 6
  406. else:
  407. self.decimals = decimals
  408. def get_value(self):
  409. self.val,self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  410. max=self.max, decimals=self.decimals)
  411. return [self.val, self.ok]
  412. # "Transform", "Enter the Angle value:"
  413. def set_value(self, val):
  414. pass
  415. class FCButton(QtWidgets.QPushButton):
  416. def __init__(self, parent=None):
  417. super(FCButton, self).__init__(parent)
  418. def get_value(self):
  419. return self.isChecked()
  420. def set_value(self, val):
  421. self.setText(str(val))
  422. class FCTab(QtWidgets.QTabWidget):
  423. def __init__(self, parent=None):
  424. super(FCTab, self).__init__(parent)
  425. self.setTabsClosable(True)
  426. self.tabCloseRequested.connect(self.closeTab)
  427. def deleteTab(self, currentIndex):
  428. widget = self.widget(currentIndex)
  429. if widget is not None:
  430. widget.deleteLater()
  431. self.removeTab(currentIndex)
  432. def closeTab(self, currentIndex):
  433. self.removeTab(currentIndex)
  434. def protectTab(self, currentIndex):
  435. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  436. class FCDetachableTab(QtWidgets.QTabWidget):
  437. # From here: https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  438. def __init__(self, parent=None):
  439. super().__init__()
  440. self.tabBar = self.FCTabBar(self)
  441. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  442. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  443. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  444. self.setTabBar(self.tabBar)
  445. # Used to keep a reference to detached tabs since their QMainWindow
  446. # does not have a parent
  447. self.detachedTabs = {}
  448. # Close all detached tabs if the application is closed explicitly
  449. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  450. self.setTabsClosable(True)
  451. self.tabCloseRequested.connect(self.closeTab)
  452. def deleteTab(self, currentIndex):
  453. widget = self.widget(currentIndex)
  454. if widget is not None:
  455. widget.deleteLater()
  456. self.removeTab(currentIndex)
  457. def closeTab(self, currentIndex):
  458. self.removeTab(currentIndex)
  459. def protectTab(self, currentIndex):
  460. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  461. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  462. ##
  463. # The default movable functionality of QTabWidget must remain disabled
  464. # so as not to conflict with the added features
  465. def setMovable(self, movable):
  466. pass
  467. ##
  468. # Move a tab from one position (index) to another
  469. #
  470. # @param fromIndex the original index location of the tab
  471. # @param toIndex the new index location of the tab
  472. @pyqtSlot(int, int)
  473. def moveTab(self, fromIndex, toIndex):
  474. widget = self.widget(fromIndex)
  475. icon = self.tabIcon(fromIndex)
  476. text = self.tabText(fromIndex)
  477. self.removeTab(fromIndex)
  478. self.insertTab(toIndex, widget, icon, text)
  479. self.setCurrentIndex(toIndex)
  480. ##
  481. # Detach the tab by removing it's contents and placing them in
  482. # a DetachedTab window
  483. #
  484. # @param index the index location of the tab to be detached
  485. # @param point the screen position for creating the new DetachedTab window
  486. @pyqtSlot(int, QtCore.QPoint)
  487. def detachTab(self, index, point):
  488. # Get the tab content
  489. name = self.tabText(index)
  490. icon = self.tabIcon(index)
  491. if icon.isNull():
  492. icon = self.window().windowIcon()
  493. contentWidget = self.widget(index)
  494. try:
  495. contentWidgetRect = contentWidget.frameGeometry()
  496. except AttributeError:
  497. return
  498. # Create a new detached tab window
  499. detachedTab = self.FCDetachedTab(name, contentWidget)
  500. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  501. detachedTab.setWindowIcon(icon)
  502. detachedTab.setGeometry(contentWidgetRect)
  503. detachedTab.onCloseSignal.connect(self.attachTab)
  504. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  505. detachedTab.move(point)
  506. detachedTab.show()
  507. # Create a reference to maintain access to the detached tab
  508. self.detachedTabs[name] = detachedTab
  509. ##
  510. # Re-attach the tab by removing the content from the DetachedTab window,
  511. # closing it, and placing the content back into the DetachableTabWidget
  512. #
  513. # @param contentWidget the content widget from the DetachedTab window
  514. # @param name the name of the detached tab
  515. # @param icon the window icon for the detached tab
  516. # @param insertAt insert the re-attached tab at the given index
  517. def attachTab(self, contentWidget, name, icon, insertAt=None):
  518. # Make the content widget a child of this widget
  519. contentWidget.setParent(self)
  520. # Remove the reference
  521. del self.detachedTabs[name]
  522. # Create an image from the given icon (for comparison)
  523. if not icon.isNull():
  524. try:
  525. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  526. tabIconImage = tabIconPixmap.toImage()
  527. except IndexError:
  528. tabIconImage = None
  529. else:
  530. tabIconImage = None
  531. # Create an image of the main window icon (for comparison)
  532. if not icon.isNull():
  533. try:
  534. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  535. windowIconImage = windowIconPixmap.toImage()
  536. except IndexError:
  537. windowIconImage = None
  538. else:
  539. windowIconImage = None
  540. # Determine if the given image and the main window icon are the same.
  541. # If they are, then do not add the icon to the tab
  542. if tabIconImage == windowIconImage:
  543. if insertAt == None:
  544. index = self.addTab(contentWidget, name)
  545. else:
  546. index = self.insertTab(insertAt, contentWidget, name)
  547. else:
  548. if insertAt == None:
  549. index = self.addTab(contentWidget, icon, name)
  550. else:
  551. index = self.insertTab(insertAt, contentWidget, icon, name)
  552. # Make this tab the current tab
  553. if index > -1:
  554. self.setCurrentIndex(index)
  555. ##
  556. # Remove the tab with the given name, even if it is detached
  557. #
  558. # @param name the name of the tab to be removed
  559. def removeTabByName(self, name):
  560. # Remove the tab if it is attached
  561. attached = False
  562. for index in range(self.count()):
  563. if str(name) == str(self.tabText(index)):
  564. self.removeTab(index)
  565. attached = True
  566. break
  567. # If the tab is not attached, close it's window and
  568. # remove the reference to it
  569. if not attached:
  570. for key in self.detachedTabs:
  571. if str(name) == str(key):
  572. self.detachedTabs[key].onCloseSignal.disconnect()
  573. self.detachedTabs[key].close()
  574. del self.detachedTabs[key]
  575. break
  576. ##
  577. # Handle dropping of a detached tab inside the DetachableTabWidget
  578. #
  579. # @param name the name of the detached tab
  580. # @param index the index of an existing tab (if the tab bar
  581. # determined that the drop occurred on an
  582. # existing tab)
  583. # @param dropPos the mouse cursor position when the drop occurred
  584. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  585. def detachedTabDrop(self, name, index, dropPos):
  586. # If the drop occurred on an existing tab, insert the detached
  587. # tab at the existing tab's location
  588. if index > -1:
  589. # Create references to the detached tab's content and icon
  590. contentWidget = self.detachedTabs[name].contentWidget
  591. icon = self.detachedTabs[name].windowIcon()
  592. # Disconnect the detached tab's onCloseSignal so that it
  593. # does not try to re-attach automatically
  594. self.detachedTabs[name].onCloseSignal.disconnect()
  595. # Close the detached
  596. self.detachedTabs[name].close()
  597. # Re-attach the tab at the given index
  598. self.attachTab(contentWidget, name, icon, index)
  599. # If the drop did not occur on an existing tab, determine if the drop
  600. # occurred in the tab bar area (the area to the side of the QTabBar)
  601. else:
  602. # Find the drop position relative to the DetachableTabWidget
  603. tabDropPos = self.mapFromGlobal(dropPos)
  604. # If the drop position is inside the DetachableTabWidget...
  605. if self.rect().contains(tabDropPos):
  606. # If the drop position is inside the tab bar area (the
  607. # area to the side of the QTabBar) or there are not tabs
  608. # currently attached...
  609. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  610. # Close the detached tab and allow it to re-attach
  611. # automatically
  612. self.detachedTabs[name].close()
  613. ##
  614. # Close all tabs that are currently detached.
  615. def closeDetachedTabs(self):
  616. listOfDetachedTabs = []
  617. for key in self.detachedTabs:
  618. listOfDetachedTabs.append(self.detachedTabs[key])
  619. for detachedTab in listOfDetachedTabs:
  620. detachedTab.close()
  621. ##
  622. # When a tab is detached, the contents are placed into this QMainWindow. The tab
  623. # can be re-attached by closing the dialog or by dragging the window into the tab bar
  624. class FCDetachedTab(QtWidgets.QMainWindow):
  625. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  626. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  627. def __init__(self, name, contentWidget):
  628. QtWidgets.QMainWindow.__init__(self, None)
  629. self.setObjectName(name)
  630. self.setWindowTitle(name)
  631. self.contentWidget = contentWidget
  632. self.setCentralWidget(self.contentWidget)
  633. self.contentWidget.show()
  634. self.windowDropFilter = self.WindowDropFilter()
  635. self.installEventFilter(self.windowDropFilter)
  636. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  637. ##
  638. # Handle a window drop event
  639. #
  640. # @param dropPos the mouse cursor position of the drop
  641. @QtCore.pyqtSlot(QtCore.QPoint)
  642. def windowDropSlot(self, dropPos):
  643. self.onDropSignal.emit(self.objectName(), dropPos)
  644. ##
  645. # If the window is closed, emit the onCloseSignal and give the
  646. # content widget back to the DetachableTabWidget
  647. #
  648. # @param event a close event
  649. def closeEvent(self, event):
  650. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  651. ##
  652. # An event filter class to detect a QMainWindow drop event
  653. class WindowDropFilter(QtCore.QObject):
  654. onDropSignal = pyqtSignal(QtCore.QPoint)
  655. def __init__(self):
  656. QtCore.QObject.__init__(self)
  657. self.lastEvent = None
  658. ##
  659. # Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  660. # event that immediately follows a Move event
  661. #
  662. # @param obj the object that generated the event
  663. # @param event the current event
  664. def eventFilter(self, obj, event):
  665. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  666. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  667. # Determine the position of the mouse cursor and emit it with the
  668. # onDropSignal
  669. mouseCursor = QtGui.QCursor()
  670. dropPos = mouseCursor.pos()
  671. self.onDropSignal.emit(dropPos)
  672. self.lastEvent = event.type()
  673. return True
  674. else:
  675. self.lastEvent = event.type()
  676. return False
  677. class FCTabBar(QtWidgets.QTabBar):
  678. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  679. onMoveTabSignal = pyqtSignal(int, int)
  680. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  681. def __init__(self, parent=None):
  682. QtWidgets.QTabBar.__init__(self, parent)
  683. self.setAcceptDrops(True)
  684. self.setElideMode(QtCore.Qt.ElideRight)
  685. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  686. self.dragStartPos = QtCore.QPoint()
  687. self.dragDropedPos = QtCore.QPoint()
  688. self.mouseCursor = QtGui.QCursor()
  689. self.dragInitiated = False
  690. # Send the onDetachTabSignal when a tab is double clicked
  691. #
  692. # @param event a mouse double click event
  693. def mouseDoubleClickEvent(self, event):
  694. event.accept()
  695. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  696. # Set the starting position for a drag event when the mouse button is pressed
  697. #
  698. # @param event a mouse press event
  699. def mousePressEvent(self, event):
  700. if event.button() == QtCore.Qt.LeftButton:
  701. self.dragStartPos = event.pos()
  702. self.dragDropedPos.setX(0)
  703. self.dragDropedPos.setY(0)
  704. self.dragInitiated = False
  705. QtWidgets.QTabBar.mousePressEvent(self, event)
  706. # Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  707. # drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  708. # bar, emit an onDetachTabSignal.
  709. #
  710. # @param event a mouse move event
  711. def mouseMoveEvent(self, event):
  712. # Determine if the current movement is detected as a drag
  713. if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  714. self.dragInitiated = True
  715. # If the current movement is a drag initiated by the left button
  716. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  717. # Stop the move event
  718. finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
  719. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  720. # Convert the move event into a drag
  721. drag = QtGui.QDrag(self)
  722. mimeData = QtCore.QMimeData()
  723. # mimeData.setData('action', 'application/tab-detach')
  724. drag.setMimeData(mimeData)
  725. # screen = QScreen(self.parentWidget().currentWidget().winId())
  726. # Create the appearance of dragging the tab content
  727. try:
  728. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  729. except Exception as e:
  730. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  731. return
  732. targetPixmap = QtGui.QPixmap(pixmap.size())
  733. targetPixmap.fill(QtCore.Qt.transparent)
  734. painter = QtGui.QPainter(targetPixmap)
  735. painter.setOpacity(0.85)
  736. painter.drawPixmap(0, 0, pixmap)
  737. painter.end()
  738. drag.setPixmap(targetPixmap)
  739. # Initiate the drag
  740. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  741. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  742. # must be set manually
  743. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  744. dropAction = QtCore.Qt.MoveAction
  745. # If the drag completed outside of the tab bar, detach the tab and move
  746. # the content to the current cursor position
  747. if dropAction == QtCore.Qt.IgnoreAction:
  748. event.accept()
  749. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  750. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  751. elif dropAction == QtCore.Qt.MoveAction:
  752. if not self.dragDropedPos.isNull():
  753. event.accept()
  754. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  755. else:
  756. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  757. # Determine if the drag has entered a tab position from another tab position
  758. #
  759. # @param event a drag enter event
  760. def dragEnterEvent(self, event):
  761. mimeData = event.mimeData()
  762. # formats = mcd imeData.formats()
  763. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  764. # event.acceptProposedAction()
  765. QtWidgets.QTabBar.dragMoveEvent(self, event)
  766. # Get the position of the end of the drag
  767. #
  768. # @param event a drop event
  769. def dropEvent(self, event):
  770. self.dragDropedPos = event.pos()
  771. QtWidgets.QTabBar.dropEvent(self, event)
  772. # Determine if the detached tab drop event occurred on an existing tab,
  773. # then send the event to the DetachableTabWidget
  774. def detachedTabDrop(self, name, dropPos):
  775. tabDropPos = self.mapFromGlobal(dropPos)
  776. index = self.tabAt(tabDropPos)
  777. self.detachedTabDropSignal.emit(name, index, dropPos)
  778. class VerticalScrollArea(QtWidgets.QScrollArea):
  779. """
  780. This widget extends QtGui.QScrollArea to make a vertical-only
  781. scroll area that also expands horizontally to accomodate
  782. its contents.
  783. """
  784. def __init__(self, parent=None):
  785. QtWidgets.QScrollArea.__init__(self, parent=parent)
  786. self.setWidgetResizable(True)
  787. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  788. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  789. def eventFilter(self, source, event):
  790. """
  791. The event filter gets automatically installed when setWidget()
  792. is called.
  793. :param source:
  794. :param event:
  795. :return:
  796. """
  797. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  798. # log.debug("VerticalScrollArea: Widget resized:")
  799. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  800. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  801. self.setMinimumWidth(self.widget().sizeHint().width() +
  802. self.verticalScrollBar().sizeHint().width())
  803. # if self.verticalScrollBar().isVisible():
  804. # log.debug(" Scroll bar visible")
  805. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  806. # self.verticalScrollBar().width())
  807. # else:
  808. # log.debug(" Scroll bar hidden")
  809. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  810. return QtWidgets.QWidget.eventFilter(self, source, event)
  811. class OptionalInputSection:
  812. def __init__(self, cb, optinputs, logic=True):
  813. """
  814. Associates the a checkbox with a set of inputs.
  815. :param cb: Checkbox that enables the optional inputs.
  816. :param optinputs: List of widgets that are optional.
  817. :param logic: When True the logic is normal, when False the logic is in reverse
  818. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  819. for logic=False, when the checkbox is checked the widgets are Disabled
  820. :return:
  821. """
  822. assert isinstance(cb, FCCheckBox), \
  823. "Expected an FCCheckBox, got %s" % type(cb)
  824. self.cb = cb
  825. self.optinputs = optinputs
  826. self.logic = logic
  827. self.on_cb_change()
  828. self.cb.stateChanged.connect(self.on_cb_change)
  829. def on_cb_change(self):
  830. if self.cb.checkState():
  831. for widget in self.optinputs:
  832. if self.logic is True:
  833. widget.setEnabled(True)
  834. else:
  835. widget.setEnabled(False)
  836. else:
  837. for widget in self.optinputs:
  838. if self.logic is True:
  839. widget.setEnabled(False)
  840. else:
  841. widget.setEnabled(True)
  842. class FCTable(QtWidgets.QTableWidget):
  843. def __init__(self, parent=None):
  844. super(FCTable, self).__init__(parent)
  845. def sizeHint(self):
  846. default_hint_size = super(FCTable, self).sizeHint()
  847. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  848. def getHeight(self):
  849. height = self.horizontalHeader().height()
  850. for i in range(self.rowCount()):
  851. height += self.rowHeight(i)
  852. return height
  853. def getWidth(self):
  854. width = self.verticalHeader().width()
  855. for i in range(self.columnCount()):
  856. width += self.columnWidth(i)
  857. return width
  858. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  859. def setColortoRow(self, rowIndex, color):
  860. for j in range(self.columnCount()):
  861. self.item(rowIndex, j).setBackground(color)
  862. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  863. def mousePressEvent(self, event):
  864. if self.itemAt(event.pos()) is None:
  865. self.clearSelection()
  866. else:
  867. QtWidgets.QTableWidget.mousePressEvent(self, event)
  868. def setupContextMenu(self):
  869. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  870. def addContextMenu(self, entry, call_function, icon=None):
  871. action_name = str(entry)
  872. action = QtWidgets.QAction(self)
  873. action.setText(action_name)
  874. if icon:
  875. assert isinstance(icon, QtGui.QIcon), \
  876. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  877. action.setIcon(icon)
  878. self.addAction(action)
  879. action.triggered.connect(call_function)
  880. class FCSpinner(QtWidgets.QSpinBox):
  881. def __init__(self, parent=None):
  882. super(FCSpinner, self).__init__(parent)
  883. def get_value(self):
  884. return str(self.value())
  885. def set_value(self, val):
  886. try:
  887. k = int(val)
  888. except Exception as e:
  889. log.debug(str(e))
  890. return
  891. self.setValue(k)
  892. # def sizeHint(self):
  893. # default_hint_size = super(FCSpinner, self).sizeHint()
  894. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  895. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  896. def __init__(self, parent=None):
  897. super(FCDoubleSpinner, self).__init__(parent)
  898. self.readyToEdit = True
  899. def mousePressEvent(self, e, parent=None):
  900. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  901. if self.readyToEdit:
  902. self.lineEdit().selectAll()
  903. self.readyToEdit = False
  904. def focusOutEvent(self, e):
  905. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  906. self.lineEdit().deselect()
  907. self.readyToEdit = True
  908. def get_value(self):
  909. return str(self.value())
  910. def set_value(self, val):
  911. try:
  912. k = int(val)
  913. except Exception as e:
  914. log.debug(str(e))
  915. return
  916. self.setValue(k)
  917. def set_precision(self, val):
  918. self.setDecimals(val)
  919. def set_range(self, min_val, max_val):
  920. self.setRange(self, min_val, max_val)
  921. class Dialog_box(QtWidgets.QWidget):
  922. def __init__(self, title=None, label=None):
  923. """
  924. :param title: string with the window title
  925. :param label: string with the message inside the dialog box
  926. """
  927. super(Dialog_box, self).__init__()
  928. self.location = (0, 0)
  929. self.ok = False
  930. dialog_box = QtWidgets.QInputDialog()
  931. dialog_box.setFixedWidth(270)
  932. self.location, self.ok = dialog_box.getText(self, title, label)