GUIElements.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. # ########################################################## ##
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 3/10/2019 #
  11. # ########################################################## ##
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. log = logging.getLogger('base')
  21. EDIT_SIZE_HINT = 70
  22. class RadioSet(QtWidgets.QWidget):
  23. activated_custom = QtCore.pyqtSignal(str)
  24. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  25. """
  26. The choices are specified as a list of dictionaries containing:
  27. * 'label': Shown in the UI
  28. * 'value': The value returned is selected
  29. :param choices: List of choices. See description.
  30. :param orientation: 'horizontal' (default) of 'vertical'.
  31. :param parent: Qt parent widget.
  32. :type choices: list
  33. """
  34. super(RadioSet, self).__init__(parent)
  35. self.choices = copy(choices)
  36. if orientation == 'horizontal':
  37. layout = QtWidgets.QHBoxLayout()
  38. else:
  39. layout = QtWidgets.QVBoxLayout()
  40. group = QtWidgets.QButtonGroup(self)
  41. for choice in self.choices:
  42. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  43. group.addButton(choice['radio'])
  44. layout.addWidget(choice['radio'], stretch=0)
  45. choice['radio'].toggled.connect(self.on_toggle)
  46. layout.setContentsMargins(0, 0, 0, 0)
  47. if stretch is False:
  48. pass
  49. else:
  50. layout.addStretch()
  51. self.setLayout(layout)
  52. self.group_toggle_fn = lambda: None
  53. def on_toggle(self):
  54. # log.debug("Radio toggled")
  55. radio = self.sender()
  56. if radio.isChecked():
  57. self.group_toggle_fn()
  58. ret_val = str(self.get_value())
  59. self.activated_custom.emit(ret_val)
  60. return
  61. def get_value(self):
  62. for choice in self.choices:
  63. if choice['radio'].isChecked():
  64. return choice['value']
  65. log.error("No button was toggled in RadioSet.")
  66. return None
  67. def set_value(self, val):
  68. for choice in self.choices:
  69. if choice['value'] == val:
  70. choice['radio'].setChecked(True)
  71. return
  72. log.error("Value given is not part of this RadioSet: %s" % str(val))
  73. # class RadioGroupChoice(QtWidgets.QWidget):
  74. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  75. # """
  76. # The choices are specified as a list of dictionaries containing:
  77. #
  78. # * 'label': Shown in the UI
  79. # * 'value': The value returned is selected
  80. #
  81. # :param choices: List of choices. See description.
  82. # :param orientation: 'horizontal' (default) of 'vertical'.
  83. # :param parent: Qt parent widget.
  84. # :type choices: list
  85. # """
  86. # super().__init__(parent)
  87. #
  88. # group = QtGui.QButtonGroup(self)
  89. #
  90. # self.lbl1 = label_1
  91. # self.lbl2 = label_2
  92. # self.hide_list = hide_list
  93. # self.show_list = show_list
  94. #
  95. # self.btn1 = QtGui.QRadioButton(str(label_1))
  96. # self.btn2 = QtGui.QRadioButton(str(label_2))
  97. # group.addButton(self.btn1)
  98. # group.addButton(self.btn2)
  99. #
  100. # if to_check == 1:
  101. # self.btn1.setChecked(True)
  102. # else:
  103. # self.btn2.setChecked(True)
  104. #
  105. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  106. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  107. #
  108. # def btn_state(self, btn):
  109. # if btn.text() == self.lbl1:
  110. # if btn.isChecked() is True:
  111. # self.show_widgets(self.show_list)
  112. # self.hide_widgets(self.hide_list)
  113. # else:
  114. # self.show_widgets(self.hide_list)
  115. # self.hide_widgets(self.show_list)
  116. #
  117. # def hide_widgets(self, lst):
  118. # for wgt in lst:
  119. # wgt.hide()
  120. #
  121. # def show_widgets(self, lst):
  122. # for wgt in lst:
  123. # wgt.show()
  124. class LengthEntry(QtWidgets.QLineEdit):
  125. def __init__(self, output_units='IN', parent=None):
  126. super(LengthEntry, self).__init__(parent)
  127. self.output_units = output_units
  128. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  129. # Unit conversion table OUTPUT-INPUT
  130. self.scales = {
  131. 'IN': {'IN': 1.0,
  132. 'MM': 1/25.4},
  133. 'MM': {'IN': 25.4,
  134. 'MM': 1.0}
  135. }
  136. self.readyToEdit = True
  137. self.editingFinished.connect(self.on_edit_finished)
  138. def on_edit_finished(self):
  139. self.clearFocus()
  140. def mousePressEvent(self, e, Parent=None):
  141. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  142. if self.readyToEdit:
  143. self.selectAll()
  144. self.readyToEdit = False
  145. def focusOutEvent(self, e):
  146. # don't focus out if the user requests an popup menu
  147. if e.reason() != QtCore.Qt.PopupFocusReason:
  148. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  149. self.deselect()
  150. self.readyToEdit = True
  151. def returnPressed(self, *args, **kwargs):
  152. val = self.get_value()
  153. if val is not None:
  154. self.set_text(str(val))
  155. else:
  156. log.warning("Could not interpret entry: %s" % self.get_text())
  157. def get_value(self):
  158. raw = str(self.text()).strip(' ')
  159. # match = self.format_re.search(raw)
  160. try:
  161. units = raw[-2:]
  162. units = self.scales[self.output_units][units.upper()]
  163. value = raw[:-2]
  164. return float(eval(value))* units
  165. except IndexError:
  166. value = raw
  167. return float(eval(value))
  168. except KeyError:
  169. value = raw
  170. return float(eval(value))
  171. except:
  172. log.warning("Could not parse value in entry: %s" % str(raw))
  173. return None
  174. def set_value(self, val):
  175. self.setText(str('%.4f' % val))
  176. def sizeHint(self):
  177. default_hint_size = super(LengthEntry, self).sizeHint()
  178. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  179. class FloatEntry(QtWidgets.QLineEdit):
  180. def __init__(self, parent=None):
  181. super(FloatEntry, self).__init__(parent)
  182. self.readyToEdit = True
  183. self.editingFinished.connect(self.on_edit_finished)
  184. def on_edit_finished(self):
  185. self.clearFocus()
  186. def mousePressEvent(self, e, Parent=None):
  187. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  188. if self.readyToEdit == True:
  189. self.selectAll()
  190. self.readyToEdit = False
  191. def focusOutEvent(self, e):
  192. # don't focus out if the user requests an popup menu
  193. if e.reason() != QtCore.Qt.PopupFocusReason:
  194. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  195. self.deselect()
  196. self.readyToEdit = True
  197. def returnPressed(self, *args, **kwargs):
  198. val = self.get_value()
  199. if val is not None:
  200. self.set_text(str(val))
  201. else:
  202. log.warning("Could not interpret entry: %s" % self.text())
  203. def get_value(self):
  204. raw = str(self.text()).strip(' ')
  205. try:
  206. evaled = eval(raw)
  207. return float(evaled)
  208. except Exception as e:
  209. if raw is not '':
  210. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  211. return None
  212. def set_value(self, val):
  213. if val is not None:
  214. self.setText("%.4f" % float(val))
  215. else:
  216. self.setText("")
  217. def sizeHint(self):
  218. default_hint_size = super(FloatEntry, self).sizeHint()
  219. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  220. class FloatEntry2(QtWidgets.QLineEdit):
  221. def __init__(self, parent=None):
  222. super(FloatEntry2, self).__init__(parent)
  223. self.readyToEdit = True
  224. self.editingFinished.connect(self.on_edit_finished)
  225. def on_edit_finished(self):
  226. self.clearFocus()
  227. def mousePressEvent(self, e, Parent=None):
  228. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  229. if self.readyToEdit:
  230. self.selectAll()
  231. self.readyToEdit = False
  232. def focusOutEvent(self, e):
  233. # don't focus out if the user requests an popup menu
  234. if e.reason() != QtCore.Qt.PopupFocusReason:
  235. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  236. self.deselect()
  237. self.readyToEdit = True
  238. def get_value(self):
  239. raw = str(self.text()).strip(' ')
  240. try:
  241. evaled = eval(raw)
  242. return float(evaled)
  243. except Exception as e:
  244. if raw is not '':
  245. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  246. return None
  247. def set_value(self, val):
  248. self.setText("%.4f" % val)
  249. def sizeHint(self):
  250. default_hint_size = super(FloatEntry2, self).sizeHint()
  251. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  252. class IntEntry(QtWidgets.QLineEdit):
  253. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  254. super(IntEntry, self).__init__(parent)
  255. self.allow_empty = allow_empty
  256. self.empty_val = empty_val
  257. self.readyToEdit = True
  258. self.editingFinished.connect(self.on_edit_finished)
  259. def on_edit_finished(self):
  260. self.clearFocus()
  261. def mousePressEvent(self, e, Parent=None):
  262. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  263. if self.readyToEdit:
  264. self.selectAll()
  265. self.readyToEdit = False
  266. def focusOutEvent(self, e):
  267. # don't focus out if the user requests an popup menu
  268. if e.reason() != QtCore.Qt.PopupFocusReason:
  269. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  270. self.deselect()
  271. self.readyToEdit = True
  272. def get_value(self):
  273. if self.allow_empty:
  274. if str(self.text()) == "":
  275. return self.empty_val
  276. # make the text() first a float and then int because if text is a float type,
  277. # the int() can't convert directly a "text float" into a int type.
  278. ret_val = float(self.text())
  279. ret_val = int(ret_val)
  280. return ret_val
  281. def set_value(self, val):
  282. if val == self.empty_val and self.allow_empty:
  283. self.setText("")
  284. return
  285. self.setText(str(val))
  286. def sizeHint(self):
  287. default_hint_size = super(IntEntry, self).sizeHint()
  288. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  289. class FCEntry(QtWidgets.QLineEdit):
  290. def __init__(self, parent=None):
  291. super(FCEntry, self).__init__(parent)
  292. self.readyToEdit = True
  293. self.editingFinished.connect(self.on_edit_finished)
  294. def on_edit_finished(self):
  295. self.clearFocus()
  296. def mousePressEvent(self, e, parent=None):
  297. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  298. if self.readyToEdit:
  299. self.selectAll()
  300. self.readyToEdit = False
  301. def focusOutEvent(self, e):
  302. if e.reason() != QtCore.Qt.PopupFocusReason:
  303. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  304. self.deselect()
  305. self.readyToEdit = True
  306. def get_value(self):
  307. return str(self.text())
  308. def set_value(self, val):
  309. if type(val) is float:
  310. self.setText('%.4f' % val)
  311. else:
  312. self.setText(str(val))
  313. def sizeHint(self):
  314. default_hint_size = super(FCEntry, self).sizeHint()
  315. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  316. class FCEntry2(FCEntry):
  317. def __init__(self, parent=None):
  318. super(FCEntry2, self).__init__(parent)
  319. def set_value(self, val, decimals=4):
  320. try:
  321. fval = float(val)
  322. except ValueError:
  323. return
  324. self.setText('%.*f' % (decimals, fval))
  325. class FCEntry3(FCEntry):
  326. def __init__(self, parent=None):
  327. super(FCEntry3, self).__init__(parent)
  328. def set_value(self, val, decimals=4):
  329. try:
  330. fval = float(val)
  331. except ValueError:
  332. return
  333. self.setText('%.*f' % (decimals, fval))
  334. def get_value(self):
  335. value = str(self.text()).strip(' ')
  336. try:
  337. return float(eval(value))
  338. except Exception as e:
  339. log.warning("Could not parse value in entry: %s" % str(e))
  340. return None
  341. class EvalEntry(QtWidgets.QLineEdit):
  342. def __init__(self, parent=None):
  343. super(EvalEntry, self).__init__(parent)
  344. self.readyToEdit = True
  345. self.editingFinished.connect(self.on_edit_finished)
  346. def on_edit_finished(self):
  347. self.clearFocus()
  348. def mousePressEvent(self, e, parent=None):
  349. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  350. if self.readyToEdit:
  351. self.selectAll()
  352. self.readyToEdit = False
  353. def focusOutEvent(self, e):
  354. if e.reason() != QtCore.Qt.PopupFocusReason:
  355. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  356. self.deselect()
  357. self.readyToEdit = True
  358. def returnPressed(self, *args, **kwargs):
  359. val = self.get_value()
  360. if val is not None:
  361. self.setText(str(val))
  362. else:
  363. log.warning("Could not interpret entry: %s" % self.get_text())
  364. def get_value(self):
  365. raw = str(self.text()).strip(' ')
  366. evaled = 0.0
  367. try:
  368. evaled = eval(raw)
  369. except Exception as e:
  370. if raw is not '':
  371. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  372. return None
  373. return evaled
  374. def set_value(self, val):
  375. self.setText(str(val))
  376. def sizeHint(self):
  377. default_hint_size = super(EvalEntry, self).sizeHint()
  378. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  379. class EvalEntry2(QtWidgets.QLineEdit):
  380. def __init__(self, parent=None):
  381. super(EvalEntry2, self).__init__(parent)
  382. self.readyToEdit = True
  383. self.editingFinished.connect(self.on_edit_finished)
  384. def on_edit_finished(self):
  385. self.clearFocus()
  386. def mousePressEvent(self, e, parent=None):
  387. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  388. if self.readyToEdit:
  389. self.selectAll()
  390. self.readyToEdit = False
  391. def focusOutEvent(self, e):
  392. if e.reason() != QtCore.Qt.PopupFocusReason:
  393. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  394. self.deselect()
  395. self.readyToEdit = True
  396. def get_value(self):
  397. raw = str(self.text()).strip(' ')
  398. evaled = 0.0
  399. try:
  400. evaled = eval(raw)
  401. except Exception as e:
  402. if raw is not '':
  403. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  404. return None
  405. return evaled
  406. def set_value(self, val):
  407. self.setText(str(val))
  408. def sizeHint(self):
  409. default_hint_size = super(EvalEntry2, self).sizeHint()
  410. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  411. class FCSpinner(QtWidgets.QSpinBox):
  412. def __init__(self, parent=None):
  413. super(FCSpinner, self).__init__(parent)
  414. self.readyToEdit = True
  415. self.editingFinished.connect(self.on_edit_finished)
  416. self.lineEdit().installEventFilter(self)
  417. def eventFilter(self, object, event):
  418. if event.type() == QtCore.QEvent.MouseButtonPress:
  419. if self.readyToEdit:
  420. self.lineEdit().selectAll()
  421. self.readyToEdit = False
  422. else:
  423. self.lineEdit().deselect()
  424. return True
  425. return False
  426. def on_edit_finished(self):
  427. self.clearFocus()
  428. # def mousePressEvent(self, e, parent=None):
  429. # super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  430. # if self.readyToEdit:
  431. # self.lineEdit().selectAll()
  432. # self.readyToEdit = False
  433. def focusOutEvent(self, e):
  434. # don't focus out if the user requests an popup menu
  435. if e.reason() != QtCore.Qt.PopupFocusReason:
  436. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  437. self.lineEdit().deselect()
  438. self.readyToEdit = True
  439. def get_value(self):
  440. return str(self.value())
  441. def set_value(self, val):
  442. try:
  443. k = int(val)
  444. except Exception as e:
  445. log.debug(str(e))
  446. return
  447. self.setValue(k)
  448. def set_range(self, min_val, max_val):
  449. self.setRange(min_val, max_val)
  450. # def sizeHint(self):
  451. # default_hint_size = super(FCSpinner, self).sizeHint()
  452. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  453. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  454. def __init__(self, parent=None):
  455. super(FCDoubleSpinner, self).__init__(parent)
  456. self.readyToEdit = True
  457. self.editingFinished.connect(self.on_edit_finished)
  458. self.lineEdit().installEventFilter(self)
  459. def eventFilter(self, object, event):
  460. if event.type() == QtCore.QEvent.MouseButtonPress:
  461. if self.readyToEdit:
  462. self.lineEdit().selectAll()
  463. self.readyToEdit = False
  464. else:
  465. self.lineEdit().deselect()
  466. return True
  467. return False
  468. def on_edit_finished(self):
  469. self.clearFocus()
  470. # def mousePressEvent(self, e, parent=None):
  471. # super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  472. # if self.readyToEdit:
  473. # self.lineEdit().selectAll()
  474. # self.readyToEdit = False
  475. def focusOutEvent(self, e):
  476. # don't focus out if the user requests an popup menu
  477. if e.reason() != QtCore.Qt.PopupFocusReason:
  478. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  479. self.lineEdit().deselect()
  480. self.readyToEdit = True
  481. def get_value(self):
  482. return str(self.value())
  483. def set_value(self, val):
  484. try:
  485. k = float(val)
  486. except Exception as e:
  487. log.debug(str(e))
  488. return
  489. self.setValue(k)
  490. def set_precision(self, val):
  491. self.setDecimals(val)
  492. def set_range(self, min_val, max_val):
  493. self.setRange(min_val, max_val)
  494. class FCCheckBox(QtWidgets.QCheckBox):
  495. def __init__(self, label='', parent=None):
  496. super(FCCheckBox, self).__init__(str(label), parent)
  497. def get_value(self):
  498. return self.isChecked()
  499. def set_value(self, val):
  500. self.setChecked(val)
  501. def toggle(self):
  502. self.set_value(not self.get_value())
  503. class FCTextArea(QtWidgets.QPlainTextEdit):
  504. def __init__(self, parent=None):
  505. super(FCTextArea, self).__init__(parent)
  506. def set_value(self, val):
  507. self.setPlainText(val)
  508. def get_value(self):
  509. return str(self.toPlainText())
  510. def sizeHint(self, custom_sizehint=None):
  511. default_hint_size = super(FCTextArea, self).sizeHint()
  512. if custom_sizehint is None:
  513. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  514. else:
  515. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  516. class FCTextAreaRich(QtWidgets.QTextEdit):
  517. def __init__(self, parent=None):
  518. super(FCTextAreaRich, self).__init__(parent)
  519. def set_value(self, val):
  520. self.setText(val)
  521. def get_value(self):
  522. return str(self.toPlainText())
  523. def sizeHint(self):
  524. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  525. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  526. class FCTextAreaExtended(QtWidgets.QTextEdit):
  527. def __init__(self, parent=None):
  528. super().__init__(parent)
  529. self.completer = MyCompleter()
  530. self.model = QtCore.QStringListModel()
  531. self.completer.setModel(self.model)
  532. self.set_model_data(keyword_list=[])
  533. self.completer.insertText.connect(self.insertCompletion)
  534. self.completer_enable = False
  535. def set_model_data(self, keyword_list):
  536. self.model.setStringList(keyword_list)
  537. def insertCompletion(self, completion):
  538. tc = self.textCursor()
  539. extra = (len(completion) - len(self.completer.completionPrefix()))
  540. # don't insert if the word is finished but add a space instead
  541. if extra == 0:
  542. tc.insertText(' ')
  543. self.completer.popup().hide()
  544. return
  545. tc.movePosition(QTextCursor.Left)
  546. tc.movePosition(QTextCursor.EndOfWord)
  547. tc.insertText(completion[-extra:])
  548. # add a space after inserting the word
  549. tc.insertText(' ')
  550. self.setTextCursor(tc)
  551. self.completer.popup().hide()
  552. def focusInEvent(self, event):
  553. if self.completer:
  554. self.completer.setWidget(self)
  555. QTextEdit.focusInEvent(self, event)
  556. def set_value(self, val):
  557. self.setText(val)
  558. def get_value(self):
  559. self.toPlainText()
  560. def insertFromMimeData(self, data):
  561. """
  562. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  563. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  564. :param data:
  565. :return:
  566. """
  567. modifier = QtWidgets.QApplication.keyboardModifiers()
  568. if modifier == Qt.ShiftModifier:
  569. text = data.text()
  570. text = text.replace('\\', '/')
  571. self.insertPlainText(text)
  572. else:
  573. self.insertPlainText(data.text())
  574. def keyPressEvent(self, event):
  575. """
  576. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  577. :param event:
  578. :return:
  579. """
  580. key = event.key()
  581. modifier = QtWidgets.QApplication.keyboardModifiers()
  582. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  583. if key == QtCore.Qt.Key_V:
  584. clipboard = QtWidgets.QApplication.clipboard()
  585. clip_text = clipboard.text()
  586. clip_text = clip_text.replace('\\', '/')
  587. self.insertPlainText(clip_text)
  588. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  589. self.comment()
  590. tc = self.textCursor()
  591. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  592. self.completer.insertText.emit(self.completer.getSelected())
  593. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  594. return
  595. elif key == Qt.Key_BraceLeft:
  596. tc.insertText('{}')
  597. self.moveCursor(QtGui.QTextCursor.Left)
  598. elif key == Qt.Key_BracketLeft:
  599. tc.insertText('[]')
  600. self.moveCursor(QtGui.QTextCursor.Left)
  601. elif key == Qt.Key_ParenLeft:
  602. tc.insertText('()')
  603. self.moveCursor(QtGui.QTextCursor.Left)
  604. elif key == Qt.Key_BraceRight:
  605. tc.select(QtGui.QTextCursor.WordUnderCursor)
  606. if tc.selectedText() == '}':
  607. tc.movePosition(QTextCursor.Right)
  608. self.setTextCursor(tc)
  609. else:
  610. tc.clearSelection()
  611. self.textCursor().insertText('}')
  612. elif key == Qt.Key_BracketRight:
  613. tc.select(QtGui.QTextCursor.WordUnderCursor)
  614. if tc.selectedText() == ']':
  615. tc.movePosition(QTextCursor.Right)
  616. self.setTextCursor(tc)
  617. else:
  618. tc.clearSelection()
  619. self.textCursor().insertText(']')
  620. elif key == Qt.Key_ParenRight:
  621. tc.select(QtGui.QTextCursor.WordUnderCursor)
  622. if tc.selectedText() == ')':
  623. tc.movePosition(QTextCursor.Right)
  624. self.setTextCursor(tc)
  625. else:
  626. tc.clearSelection()
  627. self.textCursor().insertText(')')
  628. else:
  629. super(FCTextAreaExtended, self).keyPressEvent(event)
  630. if self.completer_enable:
  631. tc.select(QTextCursor.WordUnderCursor)
  632. cr = self.cursorRect()
  633. if len(tc.selectedText()) > 0:
  634. self.completer.setCompletionPrefix(tc.selectedText())
  635. popup = self.completer.popup()
  636. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  637. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  638. + self.completer.popup().verticalScrollBar().sizeHint().width())
  639. self.completer.complete(cr)
  640. else:
  641. self.completer.popup().hide()
  642. def comment(self):
  643. """
  644. Got it from here:
  645. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  646. :return:
  647. """
  648. pos = self.textCursor().position()
  649. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  650. line_text = self.textCursor().block().text()
  651. if self.textCursor().block().text().startswith(" "):
  652. # skip the white space
  653. self.moveCursor(QtGui.QTextCursor.NextWord)
  654. self.moveCursor(QtGui.QTextCursor.NextCharacter,QtGui.QTextCursor.KeepAnchor)
  655. character = self.textCursor().selectedText()
  656. if character == "#":
  657. # delete #
  658. self.textCursor().deletePreviousChar()
  659. # delete white space
  660. self.moveCursor(QtGui.QTextCursor.NextWord,QtGui.QTextCursor.KeepAnchor)
  661. self.textCursor().removeSelectedText()
  662. else:
  663. self.moveCursor(QtGui.QTextCursor.PreviousCharacter,QtGui.QTextCursor.KeepAnchor)
  664. self.textCursor().insertText("# ")
  665. cursor = QtGui.QTextCursor(self.textCursor())
  666. cursor.setPosition(pos)
  667. self.setTextCursor(cursor)
  668. class FCComboBox(QtWidgets.QComboBox):
  669. def __init__(self, parent=None, callback=None):
  670. super(FCComboBox, self).__init__(parent)
  671. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  672. self.view = self.view()
  673. self.view.viewport().installEventFilter(self)
  674. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  675. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  676. # pos = mouse right click click position
  677. # self = is the combobox object itself
  678. if callback:
  679. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  680. def eventFilter(self, obj, event):
  681. if event.type() == QtCore.QEvent.MouseButtonRelease:
  682. if event.button() == Qt.RightButton:
  683. return True
  684. return False
  685. def wheelEvent(self, *args, **kwargs):
  686. pass
  687. def get_value(self):
  688. return str(self.currentText())
  689. def set_value(self, val):
  690. self.setCurrentIndex(self.findText(str(val)))
  691. class FCInputDialog(QtWidgets.QInputDialog):
  692. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  693. init_val=None):
  694. super(FCInputDialog, self).__init__(parent)
  695. self.allow_empty = ok
  696. self.empty_val = val
  697. self.val = 0.0
  698. self.ok = ''
  699. self.init_value = init_val if init_val else 0.0
  700. if title is None:
  701. self.title = 'title'
  702. else:
  703. self.title = title
  704. if text is None:
  705. self.text = 'text'
  706. else:
  707. self.text = text
  708. if min is None:
  709. self.min = 0
  710. else:
  711. self.min = min
  712. if max is None:
  713. self.max = 0
  714. else:
  715. self.max = max
  716. if decimals is None:
  717. self.decimals = 6
  718. else:
  719. self.decimals = decimals
  720. def get_value(self):
  721. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  722. max=self.max, decimals=self.decimals, value=self.init_value)
  723. return [self.val, self.ok]
  724. # "Transform", "Enter the Angle value:"
  725. def set_value(self, val):
  726. pass
  727. class FCButton(QtWidgets.QPushButton):
  728. def __init__(self, parent=None):
  729. super(FCButton, self).__init__(parent)
  730. def get_value(self):
  731. return self.isChecked()
  732. def set_value(self, val):
  733. self.setText(str(val))
  734. class FCMenu(QtWidgets.QMenu):
  735. def __init__(self):
  736. super().__init__()
  737. self.mouse_is_panning = False
  738. def popup(self, pos, action=None):
  739. self.mouse_is_panning = False
  740. super().popup(pos)
  741. class FCTab(QtWidgets.QTabWidget):
  742. def __init__(self, parent=None):
  743. super(FCTab, self).__init__(parent)
  744. self.setTabsClosable(True)
  745. self.tabCloseRequested.connect(self.closeTab)
  746. def deleteTab(self, currentIndex):
  747. widget = self.widget(currentIndex)
  748. if widget is not None:
  749. widget.deleteLater()
  750. self.removeTab(currentIndex)
  751. def closeTab(self, currentIndex):
  752. self.removeTab(currentIndex)
  753. def protectTab(self, currentIndex):
  754. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  755. # class FCTabBar(QtWidgets.QTabBar):
  756. # def tabSizeHint(self, index):
  757. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  758. # w = int(self.width()/self.count())
  759. # return QtCore.QSize(w, size.height())
  760. class FCDetachableTab(QtWidgets.QTabWidget):
  761. """
  762. From here:
  763. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  764. """
  765. def __init__(self, protect=None, protect_by_name=None, parent=None):
  766. super().__init__()
  767. self.tabBar = self.FCTabBar(self)
  768. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  769. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  770. self.set_detachable(val=True)
  771. self.setTabBar(self.tabBar)
  772. # Used to keep a reference to detached tabs since their QMainWindow
  773. # does not have a parent
  774. self.detachedTabs = {}
  775. # a way to make sure that tabs can't be closed after they attach to the parent tab
  776. self.protect_tab = True if protect is not None and protect is True else False
  777. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  778. # Close all detached tabs if the application is closed explicitly
  779. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  780. # used by the property self.useOldIndex(param)
  781. self.use_old_index = None
  782. self.old_index = None
  783. self.setTabsClosable(True)
  784. self.tabCloseRequested.connect(self.closeTab)
  785. def set_rmb_callback(self, callback):
  786. """
  787. :param callback: Function to call on right mouse click on tab
  788. :type callback: func
  789. :return: None
  790. """
  791. self.tabBar.right_click.connect(callback)
  792. def set_detachable(self, val=True):
  793. try:
  794. self.tabBar.onDetachTabSignal.disconnect()
  795. except TypeError:
  796. pass
  797. if val is True:
  798. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  799. # the tab can be moved around
  800. self.tabBar.can_be_dragged = True
  801. else:
  802. # the detached tab can't be moved
  803. self.tabBar.can_be_dragged = False
  804. return val
  805. def setupContextMenu(self):
  806. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  807. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  808. action_name = str(entry)
  809. action = QtWidgets.QAction(self)
  810. action.setCheckable(True)
  811. action.setText(action_name)
  812. if icon:
  813. assert isinstance(icon, QtGui.QIcon), \
  814. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  815. action.setIcon(icon)
  816. action.setChecked(initial_checked)
  817. self.addAction(action)
  818. action.triggered.connect(call_function)
  819. def useOldIndex(self, param):
  820. if param:
  821. self.use_old_index = True
  822. else:
  823. self.use_old_index = False
  824. def deleteTab(self, currentIndex):
  825. widget = self.widget(currentIndex)
  826. if widget is not None:
  827. widget.deleteLater()
  828. self.removeTab(currentIndex)
  829. def closeTab(self, currentIndex):
  830. """
  831. Slot connected to the tabCloseRequested signal
  832. :param currentIndex:
  833. :return:
  834. """
  835. self.removeTab(currentIndex)
  836. def protectTab(self, currentIndex):
  837. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  838. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  839. def setMovable(self, movable):
  840. """
  841. The default movable functionality of QTabWidget must remain disabled
  842. so as not to conflict with the added features
  843. :param movable:
  844. :return:
  845. """
  846. pass
  847. @pyqtSlot(int, int)
  848. def moveTab(self, fromIndex, toIndex):
  849. """
  850. Move a tab from one position (index) to another
  851. :param fromIndex: the original index location of the tab
  852. :param toIndex: the new index location of the tab
  853. :return:
  854. """
  855. widget = self.widget(fromIndex)
  856. icon = self.tabIcon(fromIndex)
  857. text = self.tabText(fromIndex)
  858. self.removeTab(fromIndex)
  859. self.insertTab(toIndex, widget, icon, text)
  860. self.setCurrentIndex(toIndex)
  861. @pyqtSlot(int, QtCore.QPoint)
  862. def detachTab(self, index, point):
  863. """
  864. Detach the tab by removing it's contents and placing them in
  865. a DetachedTab window
  866. :param index: the index location of the tab to be detached
  867. :param point: the screen position for creating the new DetachedTab window
  868. :return:
  869. """
  870. self.old_index = index
  871. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  872. name = "FlatCAM " + self.tabText(index)
  873. icon = self.tabIcon(index)
  874. if icon.isNull():
  875. icon = self.window().windowIcon()
  876. contentWidget = self.widget(index)
  877. try:
  878. contentWidgetRect = contentWidget.frameGeometry()
  879. except AttributeError:
  880. return
  881. # Create a new detached tab window
  882. detachedTab = self.FCDetachedTab(name, contentWidget)
  883. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  884. detachedTab.setWindowIcon(icon)
  885. detachedTab.setGeometry(contentWidgetRect)
  886. detachedTab.onCloseSignal.connect(self.attachTab)
  887. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  888. detachedTab.move(point)
  889. detachedTab.show()
  890. # Create a reference to maintain access to the detached tab
  891. self.detachedTabs[name] = detachedTab
  892. def attachTab(self, contentWidget, name, icon, insertAt=None):
  893. """
  894. Re-attach the tab by removing the content from the DetachedTab window,
  895. closing it, and placing the content back into the DetachableTabWidget
  896. :param contentWidget: the content widget from the DetachedTab window
  897. :param name: the name of the detached tab
  898. :param icon: the window icon for the detached tab
  899. :param insertAt: insert the re-attached tab at the given index
  900. :return:
  901. """
  902. # Make the content widget a child of this widget
  903. contentWidget.setParent(self)
  904. # Remove the reference
  905. del self.detachedTabs[name]
  906. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  907. name = name.partition(' ')[2]
  908. # helps in restoring the tab to the same index that it was before was detached
  909. insert_index = self.old_index if self.use_old_index is True else insertAt
  910. # Create an image from the given icon (for comparison)
  911. if not icon.isNull():
  912. try:
  913. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  914. tabIconImage = tabIconPixmap.toImage()
  915. except IndexError:
  916. tabIconImage = None
  917. else:
  918. tabIconImage = None
  919. # Create an image of the main window icon (for comparison)
  920. if not icon.isNull():
  921. try:
  922. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  923. windowIconImage = windowIconPixmap.toImage()
  924. except IndexError:
  925. windowIconImage = None
  926. else:
  927. windowIconImage = None
  928. # Determine if the given image and the main window icon are the same.
  929. # If they are, then do not add the icon to the tab
  930. if tabIconImage == windowIconImage:
  931. if insert_index is None:
  932. index = self.addTab(contentWidget, name)
  933. else:
  934. index = self.insertTab(insert_index, contentWidget, name)
  935. else:
  936. if insert_index is None:
  937. index = self.addTab(contentWidget, icon, name)
  938. else:
  939. index = self.insertTab(insert_index, contentWidget, icon, name)
  940. # on reattaching the tab if protect is true then the closure button is not added
  941. if self.protect_tab is True:
  942. self.protectTab(index)
  943. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  944. if self.protect_by_name is not None:
  945. for tab_name in self.protect_by_name:
  946. for index in range(self.count()):
  947. if str(tab_name) == str(self.tabText(index)):
  948. self.protectTab(index)
  949. # Make this tab the current tab
  950. if index > -1:
  951. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  952. def removeTabByName(self, name):
  953. """
  954. Remove the tab with the given name, even if it is detached
  955. :param name: the name of the tab to be removed
  956. :return:
  957. """
  958. # Remove the tab if it is attached
  959. attached = False
  960. for index in range(self.count()):
  961. if str(name) == str(self.tabText(index)):
  962. self.removeTab(index)
  963. attached = True
  964. break
  965. # If the tab is not attached, close it's window and
  966. # remove the reference to it
  967. if not attached:
  968. for key in self.detachedTabs:
  969. if str(name) == str(key):
  970. self.detachedTabs[key].onCloseSignal.disconnect()
  971. self.detachedTabs[key].close()
  972. del self.detachedTabs[key]
  973. break
  974. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  975. def detachedTabDrop(self, name, index, dropPos):
  976. """
  977. Handle dropping of a detached tab inside the DetachableTabWidget
  978. :param name: the name of the detached tab
  979. :param index: the index of an existing tab (if the tab bar
  980. # determined that the drop occurred on an
  981. # existing tab)
  982. :param dropPos: the mouse cursor position when the drop occurred
  983. :return:
  984. """
  985. # If the drop occurred on an existing tab, insert the detached
  986. # tab at the existing tab's location
  987. if index > -1:
  988. # Create references to the detached tab's content and icon
  989. contentWidget = self.detachedTabs[name].contentWidget
  990. icon = self.detachedTabs[name].windowIcon()
  991. # Disconnect the detached tab's onCloseSignal so that it
  992. # does not try to re-attach automatically
  993. self.detachedTabs[name].onCloseSignal.disconnect()
  994. # Close the detached
  995. self.detachedTabs[name].close()
  996. # Re-attach the tab at the given index
  997. self.attachTab(contentWidget, name, icon, index)
  998. # If the drop did not occur on an existing tab, determine if the drop
  999. # occurred in the tab bar area (the area to the side of the QTabBar)
  1000. else:
  1001. # Find the drop position relative to the DetachableTabWidget
  1002. tabDropPos = self.mapFromGlobal(dropPos)
  1003. # If the drop position is inside the DetachableTabWidget...
  1004. if self.rect().contains(tabDropPos):
  1005. # If the drop position is inside the tab bar area (the
  1006. # area to the side of the QTabBar) or there are not tabs
  1007. # currently attached...
  1008. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1009. # Close the detached tab and allow it to re-attach
  1010. # automatically
  1011. self.detachedTabs[name].close()
  1012. def closeDetachedTabs(self):
  1013. """
  1014. Close all tabs that are currently detached.
  1015. :return:
  1016. """
  1017. listOfDetachedTabs = []
  1018. for key in self.detachedTabs:
  1019. listOfDetachedTabs.append(self.detachedTabs[key])
  1020. for detachedTab in listOfDetachedTabs:
  1021. detachedTab.close()
  1022. class FCDetachedTab(QtWidgets.QMainWindow):
  1023. """
  1024. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1025. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1026. """
  1027. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1028. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  1029. def __init__(self, name, contentWidget):
  1030. QtWidgets.QMainWindow.__init__(self, None)
  1031. self.setObjectName(name)
  1032. self.setWindowTitle(name)
  1033. self.contentWidget = contentWidget
  1034. self.setCentralWidget(self.contentWidget)
  1035. self.contentWidget.show()
  1036. self.windowDropFilter = self.WindowDropFilter()
  1037. self.installEventFilter(self.windowDropFilter)
  1038. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1039. @QtCore.pyqtSlot(QtCore.QPoint)
  1040. def windowDropSlot(self, dropPos):
  1041. """
  1042. Handle a window drop event
  1043. :param dropPos: the mouse cursor position of the drop
  1044. :return:
  1045. """
  1046. self.onDropSignal.emit(self.objectName(), dropPos)
  1047. def closeEvent(self, event):
  1048. """
  1049. If the window is closed, emit the onCloseSignal and give the
  1050. content widget back to the DetachableTabWidget
  1051. :param event: a close event
  1052. :return:
  1053. """
  1054. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1055. class WindowDropFilter(QtCore.QObject):
  1056. """
  1057. An event filter class to detect a QMainWindow drop event
  1058. """
  1059. onDropSignal = pyqtSignal(QtCore.QPoint)
  1060. def __init__(self):
  1061. QtCore.QObject.__init__(self)
  1062. self.lastEvent = None
  1063. def eventFilter(self, obj, event):
  1064. """
  1065. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1066. event that immediately follows a Move event
  1067. :param obj: the object that generated the event
  1068. :param event: the current event
  1069. :return:
  1070. """
  1071. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1072. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1073. # Determine the position of the mouse cursor and emit it with the
  1074. # onDropSignal
  1075. mouseCursor = QtGui.QCursor()
  1076. dropPos = mouseCursor.pos()
  1077. self.onDropSignal.emit(dropPos)
  1078. self.lastEvent = event.type()
  1079. return True
  1080. else:
  1081. self.lastEvent = event.type()
  1082. return False
  1083. class FCTabBar(QtWidgets.QTabBar):
  1084. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  1085. onMoveTabSignal = pyqtSignal(int, int)
  1086. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  1087. right_click = pyqtSignal(int)
  1088. def __init__(self, parent=None):
  1089. QtWidgets.QTabBar.__init__(self, parent)
  1090. self.setAcceptDrops(True)
  1091. self.setElideMode(QtCore.Qt.ElideRight)
  1092. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1093. self.prev_index = -1
  1094. self.dragStartPos = QtCore.QPoint()
  1095. self.dragDropedPos = QtCore.QPoint()
  1096. self.mouseCursor = QtGui.QCursor()
  1097. self.dragInitiated = False
  1098. # set this to False and the tab will no longer be displayed as detached
  1099. self.can_be_dragged = True
  1100. def mouseDoubleClickEvent(self, event):
  1101. """
  1102. Send the onDetachTabSignal when a tab is double clicked
  1103. :param event: a mouse double click event
  1104. :return:
  1105. """
  1106. event.accept()
  1107. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1108. def mousePressEvent(self, event):
  1109. """
  1110. Set the starting position for a drag event when the left mouse button is pressed.
  1111. Start detection of a right mouse click.
  1112. :param event: a mouse press event
  1113. :return:
  1114. """
  1115. if event.button() == QtCore.Qt.LeftButton:
  1116. self.dragStartPos = event.pos()
  1117. elif event.button() == QtCore.Qt.RightButton:
  1118. self.prev_index = self.tabAt(event.pos())
  1119. self.dragDropedPos.setX(0)
  1120. self.dragDropedPos.setY(0)
  1121. self.dragInitiated = False
  1122. QtWidgets.QTabBar.mousePressEvent(self, event)
  1123. def mouseReleaseEvent(self, event):
  1124. """
  1125. Finish the detection of the right mouse click on the tab
  1126. :param event: a mouse press event
  1127. :return:
  1128. """
  1129. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1130. self.right_click.emit(self.prev_index)
  1131. self.prev_index = -1
  1132. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1133. def mouseMoveEvent(self, event):
  1134. """
  1135. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1136. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1137. bar, emit an onDetachTabSignal.
  1138. :param event: a mouse move event
  1139. :return:
  1140. """
  1141. # Determine if the current movement is detected as a drag
  1142. if not self.dragStartPos.isNull() and \
  1143. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1144. self.dragInitiated = True
  1145. # If the current movement is a drag initiated by the left button
  1146. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated and self.can_be_dragged):
  1147. # Stop the move event
  1148. finishMoveEvent = QtGui.QMouseEvent(
  1149. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1150. )
  1151. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1152. # Convert the move event into a drag
  1153. drag = QtGui.QDrag(self)
  1154. mimeData = QtCore.QMimeData()
  1155. # mimeData.setData('action', 'application/tab-detach')
  1156. drag.setMimeData(mimeData)
  1157. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1158. # Create the appearance of dragging the tab content
  1159. try:
  1160. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1161. except Exception as e:
  1162. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1163. return
  1164. targetPixmap = QtGui.QPixmap(pixmap.size())
  1165. targetPixmap.fill(QtCore.Qt.transparent)
  1166. painter = QtGui.QPainter(targetPixmap)
  1167. painter.setOpacity(0.85)
  1168. painter.drawPixmap(0, 0, pixmap)
  1169. painter.end()
  1170. drag.setPixmap(targetPixmap)
  1171. # Initiate the drag
  1172. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1173. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1174. # must be set manually
  1175. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1176. dropAction = QtCore.Qt.MoveAction
  1177. # If the drag completed outside of the tab bar, detach the tab and move
  1178. # the content to the current cursor position
  1179. if dropAction == QtCore.Qt.IgnoreAction:
  1180. event.accept()
  1181. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1182. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1183. elif dropAction == QtCore.Qt.MoveAction:
  1184. if not self.dragDropedPos.isNull():
  1185. event.accept()
  1186. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1187. else:
  1188. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1189. def dragEnterEvent(self, event):
  1190. """
  1191. Determine if the drag has entered a tab position from another tab position
  1192. :param event: a drag enter event
  1193. :return:
  1194. """
  1195. mimeData = event.mimeData()
  1196. # formats = mcd imeData.formats()
  1197. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1198. # event.acceptProposedAction()
  1199. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1200. def dropEvent(self, event):
  1201. """
  1202. Get the position of the end of the drag
  1203. :param event: a drop event
  1204. :return:
  1205. """
  1206. self.dragDropedPos = event.pos()
  1207. QtWidgets.QTabBar.dropEvent(self, event)
  1208. def detachedTabDrop(self, name, dropPos):
  1209. """
  1210. Determine if the detached tab drop event occurred on an existing tab,
  1211. then send the event to the DetachableTabWidget
  1212. :param name:
  1213. :param dropPos:
  1214. :return:
  1215. """
  1216. tabDropPos = self.mapFromGlobal(dropPos)
  1217. index = self.tabAt(tabDropPos)
  1218. self.detachedTabDropSignal.emit(name, index, dropPos)
  1219. class FCDetachableTab2(FCDetachableTab):
  1220. tab_closed_signal = pyqtSignal()
  1221. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1222. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1223. def closeTab(self, currentIndex):
  1224. """
  1225. Slot connected to the tabCloseRequested signal
  1226. :param currentIndex:
  1227. :return:
  1228. """
  1229. idx = self.currentIndex()
  1230. # emit the signal only if the name is the one we want; the name should be a parameter somehow
  1231. if self.tabText(idx) == _("Preferences"):
  1232. self.tab_closed_signal.emit()
  1233. self.removeTab(currentIndex)
  1234. class VerticalScrollArea(QtWidgets.QScrollArea):
  1235. """
  1236. This widget extends QtGui.QScrollArea to make a vertical-only
  1237. scroll area that also expands horizontally to accomodate
  1238. its contents.
  1239. """
  1240. def __init__(self, parent=None):
  1241. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1242. self.setWidgetResizable(True)
  1243. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1244. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1245. def eventFilter(self, source, event):
  1246. """
  1247. The event filter gets automatically installed when setWidget()
  1248. is called.
  1249. :param source:
  1250. :param event:
  1251. :return:
  1252. """
  1253. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1254. # log.debug("VerticalScrollArea: Widget resized:")
  1255. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1256. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1257. self.setMinimumWidth(self.widget().sizeHint().width() +
  1258. self.verticalScrollBar().sizeHint().width())
  1259. # if self.verticalScrollBar().isVisible():
  1260. # log.debug(" Scroll bar visible")
  1261. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1262. # self.verticalScrollBar().width())
  1263. # else:
  1264. # log.debug(" Scroll bar hidden")
  1265. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1266. return QtWidgets.QWidget.eventFilter(self, source, event)
  1267. class OptionalInputSection:
  1268. def __init__(self, cb, optinputs, logic=True):
  1269. """
  1270. Associates the a checkbox with a set of inputs.
  1271. :param cb: Checkbox that enables the optional inputs.
  1272. :param optinputs: List of widgets that are optional.
  1273. :param logic: When True the logic is normal, when False the logic is in reverse
  1274. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1275. for logic=False, when the checkbox is checked the widgets are Disabled
  1276. :return:
  1277. """
  1278. assert isinstance(cb, FCCheckBox), \
  1279. "Expected an FCCheckBox, got %s" % type(cb)
  1280. self.cb = cb
  1281. self.optinputs = optinputs
  1282. self.logic = logic
  1283. self.on_cb_change()
  1284. self.cb.stateChanged.connect(self.on_cb_change)
  1285. def on_cb_change(self):
  1286. if self.cb.checkState():
  1287. for widget in self.optinputs:
  1288. if self.logic is True:
  1289. widget.setEnabled(True)
  1290. else:
  1291. widget.setEnabled(False)
  1292. else:
  1293. for widget in self.optinputs:
  1294. if self.logic is True:
  1295. widget.setEnabled(False)
  1296. else:
  1297. widget.setEnabled(True)
  1298. class OptionalHideInputSection:
  1299. def __init__(self, cb, optinputs, logic=True):
  1300. """
  1301. Associates the a checkbox with a set of inputs.
  1302. :param cb: Checkbox that enables the optional inputs.
  1303. :param optinputs: List of widgets that are optional.
  1304. :param logic: When True the logic is normal, when False the logic is in reverse
  1305. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1306. for logic=False, when the checkbox is checked the widgets are Disabled
  1307. :return:
  1308. """
  1309. assert isinstance(cb, FCCheckBox), \
  1310. "Expected an FCCheckBox, got %s" % type(cb)
  1311. self.cb = cb
  1312. self.optinputs = optinputs
  1313. self.logic = logic
  1314. self.on_cb_change()
  1315. self.cb.stateChanged.connect(self.on_cb_change)
  1316. def on_cb_change(self):
  1317. if self.cb.checkState():
  1318. for widget in self.optinputs:
  1319. if self.logic is True:
  1320. widget.show()
  1321. else:
  1322. widget.hide()
  1323. else:
  1324. for widget in self.optinputs:
  1325. if self.logic is True:
  1326. widget.hide()
  1327. else:
  1328. widget.show()
  1329. class FCTable(QtWidgets.QTableWidget):
  1330. def __init__(self, parent=None):
  1331. super(FCTable, self).__init__(parent)
  1332. def sizeHint(self):
  1333. default_hint_size = super(FCTable, self).sizeHint()
  1334. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1335. def getHeight(self):
  1336. height = self.horizontalHeader().height()
  1337. for i in range(self.rowCount()):
  1338. height += self.rowHeight(i)
  1339. return height
  1340. def getWidth(self):
  1341. width = self.verticalHeader().width()
  1342. for i in range(self.columnCount()):
  1343. width += self.columnWidth(i)
  1344. return width
  1345. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpfa
  1346. def setColortoRow(self, rowIndex, color):
  1347. for j in range(self.columnCount()):
  1348. self.item(rowIndex, j).setBackground(color)
  1349. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1350. def mousePressEvent(self, event):
  1351. if self.itemAt(event.pos()) is None:
  1352. self.clearSelection()
  1353. else:
  1354. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1355. def setupContextMenu(self):
  1356. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1357. def addContextMenu(self, entry, call_function, icon=None):
  1358. action_name = str(entry)
  1359. action = QtWidgets.QAction(self)
  1360. action.setText(action_name)
  1361. if icon:
  1362. assert isinstance(icon, QtGui.QIcon), \
  1363. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1364. action.setIcon(icon)
  1365. self.addAction(action)
  1366. action.triggered.connect(call_function)
  1367. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1368. def __init__(self, units):
  1369. super(SpinBoxDelegate, self).__init__()
  1370. self.units = units
  1371. self.current_value = None
  1372. def createEditor(self, parent, option, index):
  1373. editor = QtWidgets.QDoubleSpinBox(parent)
  1374. editor.setMinimum(-999.9999)
  1375. editor.setMaximum(999.9999)
  1376. if self.units == 'MM':
  1377. editor.setDecimals(2)
  1378. else:
  1379. editor.setDecimals(3)
  1380. return editor
  1381. def setEditorData(self, spinBox, index):
  1382. try:
  1383. value = float(index.model().data(index, Qt.EditRole))
  1384. except ValueError:
  1385. value = self.current_value
  1386. # return
  1387. spinBox.setValue(value)
  1388. def setModelData(self, spinBox, model, index):
  1389. spinBox.interpretText()
  1390. value = spinBox.value()
  1391. self.current_value = value
  1392. model.setData(index, value, Qt.EditRole)
  1393. def updateEditorGeometry(self, editor, option, index):
  1394. editor.setGeometry(option.rect)
  1395. def setDecimals(self, spinbox, digits):
  1396. spinbox.setDecimals(digits)
  1397. class Dialog_box(QtWidgets.QWidget):
  1398. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  1399. """
  1400. :param title: string with the window title
  1401. :param label: string with the message inside the dialog box
  1402. """
  1403. super(Dialog_box, self).__init__()
  1404. if initial_text is None:
  1405. self.location = str((0, 0))
  1406. else:
  1407. self.location = initial_text
  1408. self.ok = False
  1409. self.dialog_box = QtWidgets.QInputDialog()
  1410. self.dialog_box.setMinimumWidth(290)
  1411. self.setWindowIcon(icon)
  1412. self.location, self.ok = self.dialog_box.getText(self, title, label,
  1413. text=str(self.location).replace('(', '').replace(')', ''))
  1414. self.readyToEdit = True
  1415. def mousePressEvent(self, e, parent=None):
  1416. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1417. if self.readyToEdit:
  1418. self.lineEdit().selectAll()
  1419. self.readyToEdit = False
  1420. def focusOutEvent(self, e):
  1421. # don't focus out if the user requests an popup menu
  1422. if e.reason() != QtCore.Qt.PopupFocusReason:
  1423. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1424. self.lineEdit().deselect()
  1425. self.readyToEdit = True
  1426. class _BrowserTextEdit(QTextEdit):
  1427. def __init__(self, version):
  1428. QTextEdit.__init__(self)
  1429. self.menu = None
  1430. self.version = version
  1431. def contextMenuEvent(self, event):
  1432. self.menu = self.createStandardContextMenu(event.pos())
  1433. clear_action = QAction("Clear", self)
  1434. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1435. self.menu.addAction(clear_action)
  1436. clear_action.triggered.connect(self.clear)
  1437. self.menu.exec_(event.globalPos())
  1438. def clear(self):
  1439. QTextEdit.clear(self)
  1440. text = "FlatCAM %s - Type >help< to get started\n\n" % self.version
  1441. text = html.escape(text)
  1442. text = text.replace('\n', '<br/>')
  1443. self.moveCursor(QTextCursor.End)
  1444. self.insertHtml(text)
  1445. class _ExpandableTextEdit(QTextEdit):
  1446. """
  1447. Class implements edit line, which expands themselves automatically
  1448. """
  1449. historyNext = pyqtSignal()
  1450. historyPrev = pyqtSignal()
  1451. def __init__(self, termwidget, *args):
  1452. QTextEdit.__init__(self, *args)
  1453. self.setStyleSheet("font: 9pt \"Courier\";")
  1454. self._fittedHeight = 1
  1455. self.textChanged.connect(self._fit_to_document)
  1456. self._fit_to_document()
  1457. self._termWidget = termwidget
  1458. self.completer = MyCompleter()
  1459. self.model = QtCore.QStringListModel()
  1460. self.completer.setModel(self.model)
  1461. self.set_model_data(keyword_list=[])
  1462. self.completer.insertText.connect(self.insertCompletion)
  1463. def set_model_data(self, keyword_list):
  1464. self.model.setStringList(keyword_list)
  1465. def insertCompletion(self, completion):
  1466. tc = self.textCursor()
  1467. extra = (len(completion) - len(self.completer.completionPrefix()))
  1468. # don't insert if the word is finished but add a space instead
  1469. if extra == 0:
  1470. tc.insertText(' ')
  1471. self.completer.popup().hide()
  1472. return
  1473. tc.movePosition(QTextCursor.Left)
  1474. tc.movePosition(QTextCursor.EndOfWord)
  1475. tc.insertText(completion[-extra:])
  1476. # add a space after inserting the word
  1477. tc.insertText(' ')
  1478. self.setTextCursor(tc)
  1479. self.completer.popup().hide()
  1480. def focusInEvent(self, event):
  1481. if self.completer:
  1482. self.completer.setWidget(self)
  1483. QTextEdit.focusInEvent(self, event)
  1484. def keyPressEvent(self, event):
  1485. """
  1486. Catch keyboard events. Process Enter, Up, Down
  1487. """
  1488. key = event.key()
  1489. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1490. self.completer.insertText.emit(self.completer.getSelected())
  1491. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1492. return
  1493. if event.matches(QKeySequence.InsertParagraphSeparator):
  1494. text = self.toPlainText()
  1495. if self._termWidget.is_command_complete(text):
  1496. self._termWidget.exec_current_command()
  1497. return
  1498. elif event.matches(QKeySequence.MoveToNextLine):
  1499. text = self.toPlainText()
  1500. cursor_pos = self.textCursor().position()
  1501. textBeforeEnd = text[cursor_pos:]
  1502. if len(textBeforeEnd.split('\n')) <= 1:
  1503. self.historyNext.emit()
  1504. return
  1505. elif event.matches(QKeySequence.MoveToPreviousLine):
  1506. text = self.toPlainText()
  1507. cursor_pos = self.textCursor().position()
  1508. text_before_start = text[:cursor_pos]
  1509. # lineCount = len(textBeforeStart.splitlines())
  1510. line_count = len(text_before_start.split('\n'))
  1511. if len(text_before_start) > 0 and \
  1512. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1513. line_count += 1
  1514. if line_count <= 1:
  1515. self.historyPrev.emit()
  1516. return
  1517. elif event.matches(QKeySequence.MoveToNextPage) or \
  1518. event.matches(QKeySequence.MoveToPreviousPage):
  1519. return self._termWidget.browser().keyPressEvent(event)
  1520. tc = self.textCursor()
  1521. QTextEdit.keyPressEvent(self, event)
  1522. tc.select(QTextCursor.WordUnderCursor)
  1523. cr = self.cursorRect()
  1524. if len(tc.selectedText()) > 0:
  1525. self.completer.setCompletionPrefix(tc.selectedText())
  1526. popup = self.completer.popup()
  1527. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1528. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1529. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1530. self.completer.complete(cr)
  1531. else:
  1532. self.completer.popup().hide()
  1533. def sizeHint(self):
  1534. """
  1535. QWidget sizeHint impelemtation
  1536. """
  1537. hint = QTextEdit.sizeHint(self)
  1538. hint.setHeight(self._fittedHeight)
  1539. return hint
  1540. def _fit_to_document(self):
  1541. """
  1542. Update widget height to fit all text
  1543. """
  1544. documentsize = self.document().size().toSize()
  1545. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1546. self.setMaximumHeight(self._fittedHeight)
  1547. self.updateGeometry()
  1548. def insertFromMimeData(self, mime_data):
  1549. # Paste only plain text.
  1550. self.insertPlainText(mime_data.text())
  1551. class MyCompleter(QCompleter):
  1552. insertText = pyqtSignal(str)
  1553. def __init__(self, parent=None):
  1554. QCompleter.__init__(self)
  1555. self.setCompletionMode(QCompleter.PopupCompletion)
  1556. self.highlighted.connect(self.setHighlighted)
  1557. # self.popup().installEventFilter(self)
  1558. # def eventFilter(self, obj, event):
  1559. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  1560. # pass
  1561. # return False
  1562. def setHighlighted(self, text):
  1563. self.lastSelected = text
  1564. def getSelected(self):
  1565. return self.lastSelected