GUIElements.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542
  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, pyqtSlot, QSettings
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QKeySequence, 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', decimals=None, 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. self.decimals = decimals if decimals is not None else 4
  139. def on_edit_finished(self):
  140. self.clearFocus()
  141. def mousePressEvent(self, e, Parent=None):
  142. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  143. if self.readyToEdit:
  144. self.selectAll()
  145. self.readyToEdit = False
  146. def focusOutEvent(self, e):
  147. # don't focus out if the user requests an popup menu
  148. if e.reason() != QtCore.Qt.PopupFocusReason:
  149. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  150. self.deselect()
  151. self.readyToEdit = True
  152. def returnPressed(self, *args, **kwargs):
  153. val = self.get_value()
  154. if val is not None:
  155. self.set_text(str(val))
  156. else:
  157. log.warning("Could not interpret entry: %s" % self.get_text())
  158. def get_value(self):
  159. raw = str(self.text()).strip(' ')
  160. # match = self.format_re.search(raw)
  161. try:
  162. units = raw[-2:]
  163. units = self.scales[self.output_units][units.upper()]
  164. value = raw[:-2]
  165. return float(eval(value))* units
  166. except IndexError:
  167. value = raw
  168. return float(eval(value))
  169. except KeyError:
  170. value = raw
  171. return float(eval(value))
  172. except Exception:
  173. log.warning("Could not parse value in entry: %s" % str(raw))
  174. return None
  175. def set_value(self, val, decimals=None):
  176. dec_digits = decimals if decimals is not None else self.decimals
  177. self.setText(str('%.*f' % (dec_digits, val)))
  178. def sizeHint(self):
  179. default_hint_size = super(LengthEntry, self).sizeHint()
  180. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  181. class FloatEntry(QtWidgets.QLineEdit):
  182. def __init__(self, decimals=None, parent=None):
  183. super(FloatEntry, self).__init__(parent)
  184. self.readyToEdit = True
  185. self.editingFinished.connect(self.on_edit_finished)
  186. self.decimals = decimals if decimals is not None else 4
  187. def on_edit_finished(self):
  188. self.clearFocus()
  189. def mousePressEvent(self, e, Parent=None):
  190. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  191. if self.readyToEdit == True:
  192. self.selectAll()
  193. self.readyToEdit = False
  194. def focusOutEvent(self, e):
  195. # don't focus out if the user requests an popup menu
  196. if e.reason() != QtCore.Qt.PopupFocusReason:
  197. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  198. self.deselect()
  199. self.readyToEdit = True
  200. def returnPressed(self, *args, **kwargs):
  201. val = self.get_value()
  202. if val is not None:
  203. self.set_text(str(val))
  204. else:
  205. log.warning("Could not interpret entry: %s" % self.text())
  206. def get_value(self):
  207. raw = str(self.text()).strip(' ')
  208. try:
  209. evaled = eval(raw)
  210. return float(evaled)
  211. except Exception as e:
  212. if raw is not '':
  213. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  214. return None
  215. def set_value(self, val, decimals=None):
  216. dig_digits = decimals if decimals is not None else self.decimals
  217. if val is not None:
  218. self.setText("%.*f" % (dig_digits, float(val)))
  219. else:
  220. self.setText("")
  221. def sizeHint(self):
  222. default_hint_size = super(FloatEntry, self).sizeHint()
  223. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  224. class FloatEntry2(QtWidgets.QLineEdit):
  225. def __init__(self, decimals=None, parent=None):
  226. super(FloatEntry2, self).__init__(parent)
  227. self.readyToEdit = True
  228. self.editingFinished.connect(self.on_edit_finished)
  229. self.decimals = decimals if decimals is not None else 4
  230. def on_edit_finished(self):
  231. self.clearFocus()
  232. def mousePressEvent(self, e, Parent=None):
  233. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  234. if self.readyToEdit:
  235. self.selectAll()
  236. self.readyToEdit = False
  237. def focusOutEvent(self, e):
  238. # don't focus out if the user requests an popup menu
  239. if e.reason() != QtCore.Qt.PopupFocusReason:
  240. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  241. self.deselect()
  242. self.readyToEdit = True
  243. def get_value(self):
  244. raw = str(self.text()).strip(' ')
  245. try:
  246. evaled = eval(raw)
  247. return float(evaled)
  248. except Exception as e:
  249. if raw is not '':
  250. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  251. return None
  252. def set_value(self, val, decimals=None):
  253. dig_digits = decimals if decimals is not None else self.decimals
  254. self.setText("%.*f" % (dig_digits, val))
  255. def sizeHint(self):
  256. default_hint_size = super(FloatEntry2, self).sizeHint()
  257. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  258. class IntEntry(QtWidgets.QLineEdit):
  259. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  260. super(IntEntry, self).__init__(parent)
  261. self.allow_empty = allow_empty
  262. self.empty_val = empty_val
  263. self.readyToEdit = True
  264. self.editingFinished.connect(self.on_edit_finished)
  265. def on_edit_finished(self):
  266. self.clearFocus()
  267. def mousePressEvent(self, e, Parent=None):
  268. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  269. if self.readyToEdit:
  270. self.selectAll()
  271. self.readyToEdit = False
  272. def focusOutEvent(self, e):
  273. # don't focus out if the user requests an popup menu
  274. if e.reason() != QtCore.Qt.PopupFocusReason:
  275. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  276. self.deselect()
  277. self.readyToEdit = True
  278. def get_value(self):
  279. if self.allow_empty:
  280. if str(self.text()) == "":
  281. return self.empty_val
  282. # make the text() first a float and then int because if text is a float type,
  283. # the int() can't convert directly a "text float" into a int type.
  284. ret_val = float(self.text())
  285. ret_val = int(ret_val)
  286. return ret_val
  287. def set_value(self, val):
  288. if val == self.empty_val and self.allow_empty:
  289. self.setText("")
  290. return
  291. self.setText(str(val))
  292. def sizeHint(self):
  293. default_hint_size = super(IntEntry, self).sizeHint()
  294. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  295. class FCEntry(QtWidgets.QLineEdit):
  296. def __init__(self, decimals=None, alignment=None, parent=None):
  297. super(FCEntry, self).__init__(parent)
  298. self.readyToEdit = True
  299. self.editingFinished.connect(self.on_edit_finished)
  300. self.decimals = decimals if decimals is not None else 4
  301. if alignment:
  302. if alignment == 'center':
  303. align_val = QtCore.Qt.AlignHCenter
  304. elif alignment == 'right':
  305. align_val = QtCore.Qt.AlignRight
  306. else:
  307. align_val = QtCore.Qt.AlignLeft
  308. self.setAlignment(align_val)
  309. def on_edit_finished(self):
  310. self.clearFocus()
  311. def mousePressEvent(self, e, parent=None):
  312. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  313. if self.readyToEdit:
  314. self.selectAll()
  315. self.readyToEdit = False
  316. def focusOutEvent(self, e):
  317. if e.reason() != QtCore.Qt.PopupFocusReason:
  318. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  319. self.deselect()
  320. self.readyToEdit = True
  321. def get_value(self):
  322. return str(self.text())
  323. def set_value(self, val, decimals=None):
  324. decimal_digits = decimals if decimals is not None else self.decimals
  325. if type(val) is float:
  326. self.setText('%.*f' % (decimal_digits, val))
  327. else:
  328. self.setText(str(val))
  329. def sizeHint(self):
  330. default_hint_size = super(FCEntry, self).sizeHint()
  331. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  332. class FCEntry2(FCEntry):
  333. def __init__(self, parent=None):
  334. super(FCEntry2, self).__init__(parent)
  335. def set_value(self, val, decimals=4):
  336. try:
  337. fval = float(val)
  338. except ValueError:
  339. return
  340. self.setText('%.*f' % (decimals, fval))
  341. class FCEntry3(FCEntry):
  342. def __init__(self, parent=None):
  343. super(FCEntry3, self).__init__(parent)
  344. def set_value(self, val, decimals=4):
  345. try:
  346. fval = float(val)
  347. except ValueError:
  348. return
  349. self.setText('%.*f' % (decimals, fval))
  350. def get_value(self):
  351. value = str(self.text()).strip(' ')
  352. try:
  353. return float(eval(value))
  354. except Exception as e:
  355. log.warning("Could not parse value in entry: %s" % str(e))
  356. return None
  357. class EvalEntry(QtWidgets.QLineEdit):
  358. def __init__(self, parent=None):
  359. super(EvalEntry, self).__init__(parent)
  360. self.readyToEdit = True
  361. self.editingFinished.connect(self.on_edit_finished)
  362. def on_edit_finished(self):
  363. self.clearFocus()
  364. def mousePressEvent(self, e, parent=None):
  365. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  366. if self.readyToEdit:
  367. self.selectAll()
  368. self.readyToEdit = False
  369. def focusOutEvent(self, e):
  370. if e.reason() != QtCore.Qt.PopupFocusReason:
  371. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  372. self.deselect()
  373. self.readyToEdit = True
  374. def returnPressed(self, *args, **kwargs):
  375. val = self.get_value()
  376. if val is not None:
  377. self.setText(str(val))
  378. else:
  379. log.warning("Could not interpret entry: %s" % self.get_text())
  380. def get_value(self):
  381. raw = str(self.text()).strip(' ')
  382. evaled = 0.0
  383. try:
  384. evaled = eval(raw)
  385. except Exception as e:
  386. if raw is not '':
  387. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  388. return None
  389. return evaled
  390. def set_value(self, val):
  391. self.setText(str(val))
  392. def sizeHint(self):
  393. default_hint_size = super(EvalEntry, self).sizeHint()
  394. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  395. class EvalEntry2(QtWidgets.QLineEdit):
  396. def __init__(self, parent=None):
  397. super(EvalEntry2, self).__init__(parent)
  398. self.readyToEdit = True
  399. self.editingFinished.connect(self.on_edit_finished)
  400. def on_edit_finished(self):
  401. self.clearFocus()
  402. def mousePressEvent(self, e, parent=None):
  403. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  404. if self.readyToEdit:
  405. self.selectAll()
  406. self.readyToEdit = False
  407. def focusOutEvent(self, e):
  408. if e.reason() != QtCore.Qt.PopupFocusReason:
  409. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  410. self.deselect()
  411. self.readyToEdit = True
  412. def get_value(self):
  413. raw = str(self.text()).strip(' ')
  414. evaled = 0.0
  415. try:
  416. evaled = eval(raw)
  417. except Exception as e:
  418. if raw is not '':
  419. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  420. return None
  421. return evaled
  422. def set_value(self, val):
  423. self.setText(str(val))
  424. def sizeHint(self):
  425. default_hint_size = super(EvalEntry2, self).sizeHint()
  426. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  427. class FCSpinner(QtWidgets.QSpinBox):
  428. returnPressed = QtCore.pyqtSignal()
  429. def __init__(self, suffix=None, alignment=None, parent=None):
  430. super(FCSpinner, self).__init__(parent)
  431. self.readyToEdit = True
  432. self.editingFinished.connect(self.on_edit_finished)
  433. self.lineEdit().installEventFilter(self)
  434. if suffix:
  435. self.setSuffix(' %s' % str(suffix))
  436. if alignment:
  437. if alignment == 'center':
  438. align_val = QtCore.Qt.AlignHCenter
  439. elif alignment == 'right':
  440. align_val = QtCore.Qt.AlignRight
  441. else:
  442. align_val = QtCore.Qt.AlignLeft
  443. self.setAlignment(align_val)
  444. self.prev_readyToEdit = True
  445. def eventFilter(self, object, event):
  446. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  447. self.prev_readyToEdit = False
  448. if self.isEnabled():
  449. if self.readyToEdit:
  450. self.lineEdit().selectAll()
  451. self.readyToEdit = False
  452. else:
  453. self.lineEdit().deselect()
  454. return True
  455. return False
  456. def keyPressEvent(self, event):
  457. if event.key() == Qt.Key_Enter:
  458. self.returnPressed.emit()
  459. self.clearFocus()
  460. else:
  461. super().keyPressEvent(event)
  462. def wheelEvent(self, *args, **kwargs):
  463. # should work only there is a focus in the lineedit of the SpinBox
  464. if self.readyToEdit is False:
  465. super().wheelEvent(*args, **kwargs)
  466. def on_edit_finished(self):
  467. self.clearFocus()
  468. self.returnPressed.emit()
  469. # def mousePressEvent(self, e, parent=None):
  470. # super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  471. # if self.readyToEdit:
  472. # self.lineEdit().selectAll()
  473. # self.readyToEdit = False
  474. def focusOutEvent(self, e):
  475. # don't focus out if the user requests an popup menu
  476. if e.reason() != QtCore.Qt.PopupFocusReason:
  477. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  478. self.lineEdit().deselect()
  479. self.readyToEdit = True
  480. def get_value(self):
  481. return int(self.value())
  482. def set_value(self, val):
  483. try:
  484. k = int(val)
  485. except Exception as e:
  486. log.debug(str(e))
  487. return
  488. self.setValue(k)
  489. def set_range(self, min_val, max_val):
  490. self.setRange(min_val, max_val)
  491. # def sizeHint(self):
  492. # default_hint_size = super(FCSpinner, self).sizeHint()
  493. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  494. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  495. returnPressed = QtCore.pyqtSignal()
  496. def __init__(self, suffix=None, alignment=None, parent=None):
  497. super(FCDoubleSpinner, self).__init__(parent)
  498. self.readyToEdit = True
  499. self.editingFinished.connect(self.on_edit_finished)
  500. self.lineEdit().installEventFilter(self)
  501. # by default don't allow the minus sign to be entered as the default for QDoubleSpinBox is the positive range
  502. # between 0.00 and 99.00 (2 decimals)
  503. self.lineEdit().setValidator(
  504. QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  505. if suffix:
  506. self.setSuffix(' %s' % str(suffix))
  507. if alignment:
  508. if alignment == 'center':
  509. align_val = QtCore.Qt.AlignHCenter
  510. elif alignment == 'right':
  511. align_val = QtCore.Qt.AlignRight
  512. else:
  513. align_val = QtCore.Qt.AlignLeft
  514. self.setAlignment(align_val)
  515. self.prev_readyToEdit = True
  516. def on_edit_finished(self):
  517. self.clearFocus()
  518. self.returnPressed.emit()
  519. def eventFilter(self, object, event):
  520. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  521. self.prev_readyToEdit = False
  522. if self.isEnabled():
  523. if self.readyToEdit:
  524. self.cursor_pos = self.lineEdit().cursorPosition()
  525. self.lineEdit().selectAll()
  526. self.readyToEdit = False
  527. else:
  528. self.lineEdit().deselect()
  529. return True
  530. return False
  531. def keyPressEvent(self, event):
  532. if event.key() == Qt.Key_Enter:
  533. self.returnPressed.emit()
  534. self.clearFocus()
  535. else:
  536. super().keyPressEvent(event)
  537. def wheelEvent(self, *args, **kwargs):
  538. # should work only there is a focus in the lineedit of the SpinBox
  539. if self.readyToEdit is False:
  540. super().wheelEvent(*args, **kwargs)
  541. def focusOutEvent(self, e):
  542. # don't focus out if the user requests an popup menu
  543. if e.reason() != QtCore.Qt.PopupFocusReason:
  544. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  545. self.lineEdit().deselect()
  546. self.readyToEdit = True
  547. self.prev_readyToEdit = True
  548. def valueFromText(self, p_str):
  549. text = p_str.replace(',', '.')
  550. try:
  551. ret_val = float(text)
  552. except ValueError:
  553. ret_val = 0.0
  554. return ret_val
  555. def validate(self, p_str, p_int):
  556. text = p_str.replace(',', '.')
  557. try:
  558. if float(text) < self.minimum() or float(text) > self.maximum():
  559. return QtGui.QValidator.Intermediate, text, p_int
  560. except ValueError:
  561. pass
  562. return QtGui.QValidator.Acceptable, p_str, p_int
  563. def get_value(self):
  564. return float(self.value())
  565. def set_value(self, val):
  566. try:
  567. k = float(val)
  568. except Exception as e:
  569. log.debug(str(e))
  570. return
  571. self.setValue(k)
  572. def set_precision(self, val):
  573. self.setDecimals(val)
  574. # make sure that the user can't type more decimals than the set precision
  575. if self.minimum() < 0 or self.maximum() < 0:
  576. self.lineEdit().setValidator(
  577. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  578. else:
  579. self.lineEdit().setValidator(
  580. QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  581. def set_range(self, min_val, max_val):
  582. if min_val < 0 or max_val < 0:
  583. self.lineEdit().setValidator(
  584. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  585. self.setRange(min_val, max_val)
  586. class FCCheckBox(QtWidgets.QCheckBox):
  587. def __init__(self, label='', parent=None):
  588. super(FCCheckBox, self).__init__(str(label), parent)
  589. def get_value(self):
  590. return self.isChecked()
  591. def set_value(self, val):
  592. self.setChecked(val)
  593. def toggle(self):
  594. self.set_value(not self.get_value())
  595. class FCTextArea(QtWidgets.QPlainTextEdit):
  596. def __init__(self, parent=None):
  597. super(FCTextArea, self).__init__(parent)
  598. def set_value(self, val):
  599. self.setPlainText(val)
  600. def get_value(self):
  601. return str(self.toPlainText())
  602. def sizeHint(self, custom_sizehint=None):
  603. default_hint_size = super(FCTextArea, self).sizeHint()
  604. if custom_sizehint is None:
  605. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  606. else:
  607. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  608. class FCTextAreaRich(QtWidgets.QTextEdit):
  609. def __init__(self, parent=None):
  610. super(FCTextAreaRich, self).__init__(parent)
  611. def set_value(self, val):
  612. self.setText(val)
  613. def get_value(self):
  614. return str(self.toPlainText())
  615. def sizeHint(self):
  616. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  617. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  618. class FCTextAreaExtended(QtWidgets.QTextEdit):
  619. def __init__(self, parent=None):
  620. super().__init__(parent)
  621. self.completer = MyCompleter()
  622. self.model = QtCore.QStringListModel()
  623. self.completer.setModel(self.model)
  624. self.set_model_data(keyword_list=[])
  625. self.completer.insertText.connect(self.insertCompletion)
  626. self.completer_enable = False
  627. def set_model_data(self, keyword_list):
  628. self.model.setStringList(keyword_list)
  629. def insertCompletion(self, completion):
  630. tc = self.textCursor()
  631. extra = (len(completion) - len(self.completer.completionPrefix()))
  632. # don't insert if the word is finished but add a space instead
  633. if extra == 0:
  634. tc.insertText(' ')
  635. self.completer.popup().hide()
  636. return
  637. tc.movePosition(QTextCursor.Left)
  638. tc.movePosition(QTextCursor.EndOfWord)
  639. tc.insertText(completion[-extra:])
  640. # add a space after inserting the word
  641. tc.insertText(' ')
  642. self.setTextCursor(tc)
  643. self.completer.popup().hide()
  644. def focusInEvent(self, event):
  645. if self.completer:
  646. self.completer.setWidget(self)
  647. QTextEdit.focusInEvent(self, event)
  648. def set_value(self, val):
  649. self.setText(val)
  650. def get_value(self):
  651. self.toPlainText()
  652. def insertFromMimeData(self, data):
  653. """
  654. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  655. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  656. :param data:
  657. :return:
  658. """
  659. modifier = QtWidgets.QApplication.keyboardModifiers()
  660. if modifier == Qt.ShiftModifier:
  661. text = data.text()
  662. text = text.replace('\\', '/')
  663. self.insertPlainText(text)
  664. else:
  665. self.insertPlainText(data.text())
  666. def keyPressEvent(self, event):
  667. """
  668. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  669. :param event:
  670. :return:
  671. """
  672. key = event.key()
  673. modifier = QtWidgets.QApplication.keyboardModifiers()
  674. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  675. if key == QtCore.Qt.Key_V:
  676. clipboard = QtWidgets.QApplication.clipboard()
  677. clip_text = clipboard.text()
  678. clip_text = clip_text.replace('\\', '/')
  679. self.insertPlainText(clip_text)
  680. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  681. self.comment()
  682. tc = self.textCursor()
  683. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  684. self.completer.insertText.emit(self.completer.getSelected())
  685. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  686. return
  687. elif key == Qt.Key_BraceLeft:
  688. tc.insertText('{}')
  689. self.moveCursor(QtGui.QTextCursor.Left)
  690. elif key == Qt.Key_BracketLeft:
  691. tc.insertText('[]')
  692. self.moveCursor(QtGui.QTextCursor.Left)
  693. elif key == Qt.Key_ParenLeft:
  694. tc.insertText('()')
  695. self.moveCursor(QtGui.QTextCursor.Left)
  696. elif key == Qt.Key_BraceRight:
  697. tc.select(QtGui.QTextCursor.WordUnderCursor)
  698. if tc.selectedText() == '}':
  699. tc.movePosition(QTextCursor.Right)
  700. self.setTextCursor(tc)
  701. else:
  702. tc.clearSelection()
  703. self.textCursor().insertText('}')
  704. elif key == Qt.Key_BracketRight:
  705. tc.select(QtGui.QTextCursor.WordUnderCursor)
  706. if tc.selectedText() == ']':
  707. tc.movePosition(QTextCursor.Right)
  708. self.setTextCursor(tc)
  709. else:
  710. tc.clearSelection()
  711. self.textCursor().insertText(']')
  712. elif key == Qt.Key_ParenRight:
  713. tc.select(QtGui.QTextCursor.WordUnderCursor)
  714. if tc.selectedText() == ')':
  715. tc.movePosition(QTextCursor.Right)
  716. self.setTextCursor(tc)
  717. else:
  718. tc.clearSelection()
  719. self.textCursor().insertText(')')
  720. else:
  721. super(FCTextAreaExtended, self).keyPressEvent(event)
  722. if self.completer_enable:
  723. tc.select(QTextCursor.WordUnderCursor)
  724. cr = self.cursorRect()
  725. if len(tc.selectedText()) > 0:
  726. self.completer.setCompletionPrefix(tc.selectedText())
  727. popup = self.completer.popup()
  728. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  729. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  730. + self.completer.popup().verticalScrollBar().sizeHint().width())
  731. self.completer.complete(cr)
  732. else:
  733. self.completer.popup().hide()
  734. def comment(self):
  735. """
  736. Got it from here:
  737. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  738. :return:
  739. """
  740. pos = self.textCursor().position()
  741. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  742. line_text = self.textCursor().block().text()
  743. if self.textCursor().block().text().startswith(" "):
  744. # skip the white space
  745. self.moveCursor(QtGui.QTextCursor.NextWord)
  746. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  747. character = self.textCursor().selectedText()
  748. if character == "#":
  749. # delete #
  750. self.textCursor().deletePreviousChar()
  751. # delete white space
  752. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  753. self.textCursor().removeSelectedText()
  754. else:
  755. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  756. self.textCursor().insertText("# ")
  757. cursor = QtGui.QTextCursor(self.textCursor())
  758. cursor.setPosition(pos)
  759. self.setTextCursor(cursor)
  760. class FCPlainTextAreaExtended(QtWidgets.QPlainTextEdit):
  761. def __init__(self, parent=None):
  762. super().__init__(parent)
  763. self.completer = MyCompleter()
  764. self.model = QtCore.QStringListModel()
  765. self.completer.setModel(self.model)
  766. self.set_model_data(keyword_list=[])
  767. self.completer.insertText.connect(self.insertCompletion)
  768. self.completer_enable = False
  769. def append(self, text):
  770. """
  771. Added this to make this subclass compatible with FCTextAreaExtended
  772. :param text: string
  773. :return:
  774. """
  775. self.appendPlainText(text)
  776. def set_model_data(self, keyword_list):
  777. self.model.setStringList(keyword_list)
  778. def insertCompletion(self, completion):
  779. tc = self.textCursor()
  780. extra = (len(completion) - len(self.completer.completionPrefix()))
  781. # don't insert if the word is finished but add a space instead
  782. if extra == 0:
  783. tc.insertText(' ')
  784. self.completer.popup().hide()
  785. return
  786. tc.movePosition(QTextCursor.Left)
  787. tc.movePosition(QTextCursor.EndOfWord)
  788. tc.insertText(completion[-extra:])
  789. # add a space after inserting the word
  790. tc.insertText(' ')
  791. self.setTextCursor(tc)
  792. self.completer.popup().hide()
  793. def focusInEvent(self, event):
  794. if self.completer:
  795. self.completer.setWidget(self)
  796. QtWidgets.QPlainTextEdit.focusInEvent(self, event)
  797. def set_value(self, val):
  798. self.setPlainText(val)
  799. def get_value(self):
  800. self.toPlainText()
  801. def insertFromMimeData(self, data):
  802. """
  803. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  804. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  805. :param data:
  806. :return:
  807. """
  808. modifier = QtWidgets.QApplication.keyboardModifiers()
  809. if modifier == Qt.ShiftModifier:
  810. text = data.text()
  811. text = text.replace('\\', '/')
  812. self.insertPlainText(text)
  813. else:
  814. self.insertPlainText(data.text())
  815. def keyPressEvent(self, event):
  816. """
  817. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  818. :param event:
  819. :return:
  820. """
  821. key = event.key()
  822. modifier = QtWidgets.QApplication.keyboardModifiers()
  823. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  824. if key == QtCore.Qt.Key_V:
  825. clipboard = QtWidgets.QApplication.clipboard()
  826. clip_text = clipboard.text()
  827. clip_text = clip_text.replace('\\', '/')
  828. self.insertPlainText(clip_text)
  829. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  830. self.comment()
  831. tc = self.textCursor()
  832. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  833. self.completer.insertText.emit(self.completer.getSelected())
  834. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  835. return
  836. elif key == Qt.Key_BraceLeft:
  837. tc.insertText('{}')
  838. self.moveCursor(QtGui.QTextCursor.Left)
  839. elif key == Qt.Key_BracketLeft:
  840. tc.insertText('[]')
  841. self.moveCursor(QtGui.QTextCursor.Left)
  842. elif key == Qt.Key_ParenLeft:
  843. tc.insertText('()')
  844. self.moveCursor(QtGui.QTextCursor.Left)
  845. elif key == Qt.Key_BraceRight:
  846. tc.select(QtGui.QTextCursor.WordUnderCursor)
  847. if tc.selectedText() == '}':
  848. tc.movePosition(QTextCursor.Right)
  849. self.setTextCursor(tc)
  850. else:
  851. tc.clearSelection()
  852. self.textCursor().insertText('}')
  853. elif key == Qt.Key_BracketRight:
  854. tc.select(QtGui.QTextCursor.WordUnderCursor)
  855. if tc.selectedText() == ']':
  856. tc.movePosition(QTextCursor.Right)
  857. self.setTextCursor(tc)
  858. else:
  859. tc.clearSelection()
  860. self.textCursor().insertText(']')
  861. elif key == Qt.Key_ParenRight:
  862. tc.select(QtGui.QTextCursor.WordUnderCursor)
  863. if tc.selectedText() == ')':
  864. tc.movePosition(QTextCursor.Right)
  865. self.setTextCursor(tc)
  866. else:
  867. tc.clearSelection()
  868. self.textCursor().insertText(')')
  869. else:
  870. super(FCPlainTextAreaExtended, self).keyPressEvent(event)
  871. if self.completer_enable:
  872. tc.select(QTextCursor.WordUnderCursor)
  873. cr = self.cursorRect()
  874. if len(tc.selectedText()) > 0:
  875. self.completer.setCompletionPrefix(tc.selectedText())
  876. popup = self.completer.popup()
  877. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  878. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  879. + self.completer.popup().verticalScrollBar().sizeHint().width())
  880. self.completer.complete(cr)
  881. else:
  882. self.completer.popup().hide()
  883. def comment(self):
  884. """
  885. Got it from here:
  886. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  887. :return:
  888. """
  889. pos = self.textCursor().position()
  890. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  891. line_text = self.textCursor().block().text()
  892. if self.textCursor().block().text().startswith(" "):
  893. # skip the white space
  894. self.moveCursor(QtGui.QTextCursor.NextWord)
  895. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  896. character = self.textCursor().selectedText()
  897. if character == "#":
  898. # delete #
  899. self.textCursor().deletePreviousChar()
  900. # delete white space
  901. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  902. self.textCursor().removeSelectedText()
  903. else:
  904. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  905. self.textCursor().insertText("# ")
  906. cursor = QtGui.QTextCursor(self.textCursor())
  907. cursor.setPosition(pos)
  908. self.setTextCursor(cursor)
  909. class FCComboBox(QtWidgets.QComboBox):
  910. def __init__(self, parent=None, callback=None):
  911. super(FCComboBox, self).__init__(parent)
  912. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  913. self.view = self.view()
  914. self.view.viewport().installEventFilter(self)
  915. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  916. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  917. # pos = mouse right click click position
  918. # self = is the combobox object itself
  919. if callback:
  920. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  921. def eventFilter(self, obj, event):
  922. if event.type() == QtCore.QEvent.MouseButtonRelease:
  923. if event.button() == Qt.RightButton:
  924. return True
  925. return False
  926. def wheelEvent(self, *args, **kwargs):
  927. pass
  928. def get_value(self):
  929. return str(self.currentText())
  930. def set_value(self, val):
  931. self.setCurrentIndex(self.findText(str(val)))
  932. class FCInputDialog(QtWidgets.QInputDialog):
  933. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  934. init_val=None):
  935. super(FCInputDialog, self).__init__(parent)
  936. self.allow_empty = ok
  937. self.empty_val = val
  938. self.val = 0.0
  939. self.ok = ''
  940. self.init_value = init_val if init_val else 0.0
  941. if title is None:
  942. self.title = 'title'
  943. else:
  944. self.title = title
  945. if text is None:
  946. self.text = 'text'
  947. else:
  948. self.text = text
  949. if min is None:
  950. self.min = 0
  951. else:
  952. self.min = min
  953. if max is None:
  954. self.max = 0
  955. else:
  956. self.max = max
  957. if decimals is None:
  958. self.decimals = 6
  959. else:
  960. self.decimals = decimals
  961. def get_value(self):
  962. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  963. max=self.max, decimals=self.decimals, value=self.init_value)
  964. return [self.val, self.ok]
  965. # "Transform", "Enter the Angle value:"
  966. def set_value(self, val):
  967. pass
  968. class FCButton(QtWidgets.QPushButton):
  969. def __init__(self, parent=None):
  970. super(FCButton, self).__init__(parent)
  971. def get_value(self):
  972. return self.isChecked()
  973. def set_value(self, val):
  974. self.setText(str(val))
  975. class FCMenu(QtWidgets.QMenu):
  976. def __init__(self):
  977. super().__init__()
  978. self.mouse_is_panning = False
  979. def popup(self, pos, action=None):
  980. self.mouse_is_panning = False
  981. super().popup(pos)
  982. class FCTab(QtWidgets.QTabWidget):
  983. def __init__(self, parent=None):
  984. super(FCTab, self).__init__(parent)
  985. self.setTabsClosable(True)
  986. self.tabCloseRequested.connect(self.closeTab)
  987. def deleteTab(self, currentIndex):
  988. widget = self.widget(currentIndex)
  989. if widget is not None:
  990. widget.deleteLater()
  991. self.removeTab(currentIndex)
  992. def closeTab(self, currentIndex):
  993. self.removeTab(currentIndex)
  994. def protectTab(self, currentIndex):
  995. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  996. # class FCTabBar(QtWidgets.QTabBar):
  997. # def tabSizeHint(self, index):
  998. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  999. # w = int(self.width()/self.count())
  1000. # return QtCore.QSize(w, size.height())
  1001. class FCDetachableTab(QtWidgets.QTabWidget):
  1002. """
  1003. From here:
  1004. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  1005. """
  1006. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1007. super().__init__()
  1008. self.tabBar = self.FCTabBar(self)
  1009. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  1010. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  1011. self.set_detachable(val=True)
  1012. self.setTabBar(self.tabBar)
  1013. # Used to keep a reference to detached tabs since their QMainWindow
  1014. # does not have a parent
  1015. self.detachedTabs = {}
  1016. # a way to make sure that tabs can't be closed after they attach to the parent tab
  1017. self.protect_tab = True if protect is not None and protect is True else False
  1018. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  1019. # Close all detached tabs if the application is closed explicitly
  1020. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  1021. # used by the property self.useOldIndex(param)
  1022. self.use_old_index = None
  1023. self.old_index = None
  1024. self.setTabsClosable(True)
  1025. self.tabCloseRequested.connect(self.closeTab)
  1026. def set_rmb_callback(self, callback):
  1027. """
  1028. :param callback: Function to call on right mouse click on tab
  1029. :type callback: func
  1030. :return: None
  1031. """
  1032. self.tabBar.right_click.connect(callback)
  1033. def set_detachable(self, val=True):
  1034. try:
  1035. self.tabBar.onDetachTabSignal.disconnect()
  1036. except TypeError:
  1037. pass
  1038. if val is True:
  1039. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  1040. # the tab can be moved around
  1041. self.tabBar.can_be_dragged = True
  1042. else:
  1043. # the detached tab can't be moved
  1044. self.tabBar.can_be_dragged = False
  1045. return val
  1046. def setupContextMenu(self):
  1047. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1048. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  1049. action_name = str(entry)
  1050. action = QtWidgets.QAction(self)
  1051. action.setCheckable(True)
  1052. action.setText(action_name)
  1053. if icon:
  1054. assert isinstance(icon, QtGui.QIcon), \
  1055. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1056. action.setIcon(icon)
  1057. action.setChecked(initial_checked)
  1058. self.addAction(action)
  1059. action.triggered.connect(call_function)
  1060. def useOldIndex(self, param):
  1061. if param:
  1062. self.use_old_index = True
  1063. else:
  1064. self.use_old_index = False
  1065. def deleteTab(self, currentIndex):
  1066. widget = self.widget(currentIndex)
  1067. if widget is not None:
  1068. widget.deleteLater()
  1069. self.removeTab(currentIndex)
  1070. def closeTab(self, currentIndex):
  1071. """
  1072. Slot connected to the tabCloseRequested signal
  1073. :param currentIndex:
  1074. :return:
  1075. """
  1076. self.removeTab(currentIndex)
  1077. def protectTab(self, currentIndex):
  1078. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1079. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1080. def setMovable(self, movable):
  1081. """
  1082. The default movable functionality of QTabWidget must remain disabled
  1083. so as not to conflict with the added features
  1084. :param movable:
  1085. :return:
  1086. """
  1087. pass
  1088. @pyqtSlot(int, int)
  1089. def moveTab(self, fromIndex, toIndex):
  1090. """
  1091. Move a tab from one position (index) to another
  1092. :param fromIndex: the original index location of the tab
  1093. :param toIndex: the new index location of the tab
  1094. :return:
  1095. """
  1096. widget = self.widget(fromIndex)
  1097. icon = self.tabIcon(fromIndex)
  1098. text = self.tabText(fromIndex)
  1099. self.removeTab(fromIndex)
  1100. self.insertTab(toIndex, widget, icon, text)
  1101. self.setCurrentIndex(toIndex)
  1102. @pyqtSlot(int, QtCore.QPoint)
  1103. def detachTab(self, index, point):
  1104. """
  1105. Detach the tab by removing it's contents and placing them in
  1106. a DetachedTab window
  1107. :param index: the index location of the tab to be detached
  1108. :param point: the screen position for creating the new DetachedTab window
  1109. :return:
  1110. """
  1111. self.old_index = index
  1112. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  1113. name = "FlatCAM " + self.tabText(index)
  1114. icon = self.tabIcon(index)
  1115. if icon.isNull():
  1116. icon = self.window().windowIcon()
  1117. contentWidget = self.widget(index)
  1118. try:
  1119. contentWidgetRect = contentWidget.frameGeometry()
  1120. except AttributeError:
  1121. return
  1122. # Create a new detached tab window
  1123. detachedTab = self.FCDetachedTab(name, contentWidget)
  1124. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  1125. detachedTab.setWindowIcon(icon)
  1126. detachedTab.setGeometry(contentWidgetRect)
  1127. detachedTab.onCloseSignal.connect(self.attachTab)
  1128. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  1129. detachedTab.move(point)
  1130. detachedTab.show()
  1131. # Create a reference to maintain access to the detached tab
  1132. self.detachedTabs[name] = detachedTab
  1133. def attachTab(self, contentWidget, name, icon, insertAt=None):
  1134. """
  1135. Re-attach the tab by removing the content from the DetachedTab window,
  1136. closing it, and placing the content back into the DetachableTabWidget
  1137. :param contentWidget: the content widget from the DetachedTab window
  1138. :param name: the name of the detached tab
  1139. :param icon: the window icon for the detached tab
  1140. :param insertAt: insert the re-attached tab at the given index
  1141. :return:
  1142. """
  1143. # Make the content widget a child of this widget
  1144. contentWidget.setParent(self)
  1145. # Remove the reference
  1146. del self.detachedTabs[name]
  1147. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  1148. name = name.partition(' ')[2]
  1149. # helps in restoring the tab to the same index that it was before was detached
  1150. insert_index = self.old_index if self.use_old_index is True else insertAt
  1151. # Create an image from the given icon (for comparison)
  1152. if not icon.isNull():
  1153. try:
  1154. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  1155. tabIconImage = tabIconPixmap.toImage()
  1156. except IndexError:
  1157. tabIconImage = None
  1158. else:
  1159. tabIconImage = None
  1160. # Create an image of the main window icon (for comparison)
  1161. if not icon.isNull():
  1162. try:
  1163. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  1164. windowIconImage = windowIconPixmap.toImage()
  1165. except IndexError:
  1166. windowIconImage = None
  1167. else:
  1168. windowIconImage = None
  1169. # Determine if the given image and the main window icon are the same.
  1170. # If they are, then do not add the icon to the tab
  1171. if tabIconImage == windowIconImage:
  1172. if insert_index is None:
  1173. index = self.addTab(contentWidget, name)
  1174. else:
  1175. index = self.insertTab(insert_index, contentWidget, name)
  1176. else:
  1177. if insert_index is None:
  1178. index = self.addTab(contentWidget, icon, name)
  1179. else:
  1180. index = self.insertTab(insert_index, contentWidget, icon, name)
  1181. # on reattaching the tab if protect is true then the closure button is not added
  1182. if self.protect_tab is True:
  1183. self.protectTab(index)
  1184. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  1185. if self.protect_by_name is not None:
  1186. for tab_name in self.protect_by_name:
  1187. for index in range(self.count()):
  1188. if str(tab_name) == str(self.tabText(index)):
  1189. self.protectTab(index)
  1190. # Make this tab the current tab
  1191. if index > -1:
  1192. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  1193. def removeTabByName(self, name):
  1194. """
  1195. Remove the tab with the given name, even if it is detached
  1196. :param name: the name of the tab to be removed
  1197. :return:
  1198. """
  1199. # Remove the tab if it is attached
  1200. attached = False
  1201. for index in range(self.count()):
  1202. if str(name) == str(self.tabText(index)):
  1203. self.removeTab(index)
  1204. attached = True
  1205. break
  1206. # If the tab is not attached, close it's window and
  1207. # remove the reference to it
  1208. if not attached:
  1209. for key in self.detachedTabs:
  1210. if str(name) == str(key):
  1211. self.detachedTabs[key].onCloseSignal.disconnect()
  1212. self.detachedTabs[key].close()
  1213. del self.detachedTabs[key]
  1214. break
  1215. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  1216. def detachedTabDrop(self, name, index, dropPos):
  1217. """
  1218. Handle dropping of a detached tab inside the DetachableTabWidget
  1219. :param name: the name of the detached tab
  1220. :param index: the index of an existing tab (if the tab bar
  1221. # determined that the drop occurred on an
  1222. # existing tab)
  1223. :param dropPos: the mouse cursor position when the drop occurred
  1224. :return:
  1225. """
  1226. # If the drop occurred on an existing tab, insert the detached
  1227. # tab at the existing tab's location
  1228. if index > -1:
  1229. # Create references to the detached tab's content and icon
  1230. contentWidget = self.detachedTabs[name].contentWidget
  1231. icon = self.detachedTabs[name].windowIcon()
  1232. # Disconnect the detached tab's onCloseSignal so that it
  1233. # does not try to re-attach automatically
  1234. self.detachedTabs[name].onCloseSignal.disconnect()
  1235. # Close the detached
  1236. self.detachedTabs[name].close()
  1237. # Re-attach the tab at the given index
  1238. self.attachTab(contentWidget, name, icon, index)
  1239. # If the drop did not occur on an existing tab, determine if the drop
  1240. # occurred in the tab bar area (the area to the side of the QTabBar)
  1241. else:
  1242. # Find the drop position relative to the DetachableTabWidget
  1243. tabDropPos = self.mapFromGlobal(dropPos)
  1244. # If the drop position is inside the DetachableTabWidget...
  1245. if self.rect().contains(tabDropPos):
  1246. # If the drop position is inside the tab bar area (the
  1247. # area to the side of the QTabBar) or there are not tabs
  1248. # currently attached...
  1249. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1250. # Close the detached tab and allow it to re-attach
  1251. # automatically
  1252. self.detachedTabs[name].close()
  1253. def closeDetachedTabs(self):
  1254. """
  1255. Close all tabs that are currently detached.
  1256. :return:
  1257. """
  1258. listOfDetachedTabs = []
  1259. for key in self.detachedTabs:
  1260. listOfDetachedTabs.append(self.detachedTabs[key])
  1261. for detachedTab in listOfDetachedTabs:
  1262. detachedTab.close()
  1263. class FCDetachedTab(QtWidgets.QMainWindow):
  1264. """
  1265. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1266. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1267. """
  1268. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1269. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  1270. def __init__(self, name, contentWidget):
  1271. QtWidgets.QMainWindow.__init__(self, None)
  1272. self.setObjectName(name)
  1273. self.setWindowTitle(name)
  1274. self.contentWidget = contentWidget
  1275. self.setCentralWidget(self.contentWidget)
  1276. self.contentWidget.show()
  1277. self.windowDropFilter = self.WindowDropFilter()
  1278. self.installEventFilter(self.windowDropFilter)
  1279. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1280. @QtCore.pyqtSlot(QtCore.QPoint)
  1281. def windowDropSlot(self, dropPos):
  1282. """
  1283. Handle a window drop event
  1284. :param dropPos: the mouse cursor position of the drop
  1285. :return:
  1286. """
  1287. self.onDropSignal.emit(self.objectName(), dropPos)
  1288. def closeEvent(self, event):
  1289. """
  1290. If the window is closed, emit the onCloseSignal and give the
  1291. content widget back to the DetachableTabWidget
  1292. :param event: a close event
  1293. :return:
  1294. """
  1295. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1296. class WindowDropFilter(QtCore.QObject):
  1297. """
  1298. An event filter class to detect a QMainWindow drop event
  1299. """
  1300. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  1301. def __init__(self):
  1302. QtCore.QObject.__init__(self)
  1303. self.lastEvent = None
  1304. def eventFilter(self, obj, event):
  1305. """
  1306. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1307. event that immediately follows a Move event
  1308. :param obj: the object that generated the event
  1309. :param event: the current event
  1310. :return:
  1311. """
  1312. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1313. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1314. # Determine the position of the mouse cursor and emit it with the
  1315. # onDropSignal
  1316. mouseCursor = QtGui.QCursor()
  1317. dropPos = mouseCursor.pos()
  1318. self.onDropSignal.emit(dropPos)
  1319. self.lastEvent = event.type()
  1320. return True
  1321. else:
  1322. self.lastEvent = event.type()
  1323. return False
  1324. class FCTabBar(QtWidgets.QTabBar):
  1325. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  1326. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  1327. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  1328. right_click = QtCore.pyqtSignal(int)
  1329. def __init__(self, parent=None):
  1330. QtWidgets.QTabBar.__init__(self, parent)
  1331. self.setAcceptDrops(True)
  1332. self.setElideMode(QtCore.Qt.ElideRight)
  1333. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1334. self.prev_index = -1
  1335. self.dragStartPos = QtCore.QPoint()
  1336. self.dragDropedPos = QtCore.QPoint()
  1337. self.mouseCursor = QtGui.QCursor()
  1338. self.dragInitiated = False
  1339. # set this to False and the tab will no longer be displayed as detached
  1340. self.can_be_dragged = True
  1341. def mouseDoubleClickEvent(self, event):
  1342. """
  1343. Send the onDetachTabSignal when a tab is double clicked
  1344. :param event: a mouse double click event
  1345. :return:
  1346. """
  1347. event.accept()
  1348. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1349. def mousePressEvent(self, event):
  1350. """
  1351. Set the starting position for a drag event when the left mouse button is pressed.
  1352. Start detection of a right mouse click.
  1353. :param event: a mouse press event
  1354. :return:
  1355. """
  1356. if event.button() == QtCore.Qt.LeftButton:
  1357. self.dragStartPos = event.pos()
  1358. elif event.button() == QtCore.Qt.RightButton:
  1359. self.prev_index = self.tabAt(event.pos())
  1360. self.dragDropedPos.setX(0)
  1361. self.dragDropedPos.setY(0)
  1362. self.dragInitiated = False
  1363. QtWidgets.QTabBar.mousePressEvent(self, event)
  1364. def mouseReleaseEvent(self, event):
  1365. """
  1366. Finish the detection of the right mouse click on the tab
  1367. :param event: a mouse press event
  1368. :return:
  1369. """
  1370. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1371. self.right_click.emit(self.prev_index)
  1372. self.prev_index = -1
  1373. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1374. def mouseMoveEvent(self, event):
  1375. """
  1376. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1377. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1378. bar, emit an onDetachTabSignal.
  1379. :param event: a mouse move event
  1380. :return:
  1381. """
  1382. # Determine if the current movement is detected as a drag
  1383. if not self.dragStartPos.isNull() and \
  1384. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1385. self.dragInitiated = True
  1386. # If the current movement is a drag initiated by the left button
  1387. if ((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated and self.can_be_dragged:
  1388. # Stop the move event
  1389. finishMoveEvent = QtGui.QMouseEvent(
  1390. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1391. )
  1392. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1393. # Convert the move event into a drag
  1394. drag = QtGui.QDrag(self)
  1395. mimeData = QtCore.QMimeData()
  1396. # mimeData.setData('action', 'application/tab-detach')
  1397. drag.setMimeData(mimeData)
  1398. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1399. # Create the appearance of dragging the tab content
  1400. try:
  1401. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1402. except Exception as e:
  1403. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1404. return
  1405. targetPixmap = QtGui.QPixmap(pixmap.size())
  1406. targetPixmap.fill(QtCore.Qt.transparent)
  1407. painter = QtGui.QPainter(targetPixmap)
  1408. painter.setOpacity(0.85)
  1409. painter.drawPixmap(0, 0, pixmap)
  1410. painter.end()
  1411. drag.setPixmap(targetPixmap)
  1412. # Initiate the drag
  1413. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1414. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1415. # must be set manually
  1416. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1417. dropAction = QtCore.Qt.MoveAction
  1418. # If the drag completed outside of the tab bar, detach the tab and move
  1419. # the content to the current cursor position
  1420. if dropAction == QtCore.Qt.IgnoreAction:
  1421. event.accept()
  1422. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1423. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1424. elif dropAction == QtCore.Qt.MoveAction:
  1425. if not self.dragDropedPos.isNull():
  1426. event.accept()
  1427. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1428. else:
  1429. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1430. def dragEnterEvent(self, event):
  1431. """
  1432. Determine if the drag has entered a tab position from another tab position
  1433. :param event: a drag enter event
  1434. :return:
  1435. """
  1436. mimeData = event.mimeData()
  1437. # formats = mcd imeData.formats()
  1438. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1439. # event.acceptProposedAction()
  1440. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1441. def dropEvent(self, event):
  1442. """
  1443. Get the position of the end of the drag
  1444. :param event: a drop event
  1445. :return:
  1446. """
  1447. self.dragDropedPos = event.pos()
  1448. QtWidgets.QTabBar.dropEvent(self, event)
  1449. def detachedTabDrop(self, name, dropPos):
  1450. """
  1451. Determine if the detached tab drop event occurred on an existing tab,
  1452. then send the event to the DetachableTabWidget
  1453. :param name:
  1454. :param dropPos:
  1455. :return:
  1456. """
  1457. tabDropPos = self.mapFromGlobal(dropPos)
  1458. index = self.tabAt(tabDropPos)
  1459. self.detachedTabDropSignal.emit(name, index, dropPos)
  1460. class FCDetachableTab2(FCDetachableTab):
  1461. tab_closed_signal = QtCore.pyqtSignal(object)
  1462. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1463. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1464. def closeTab(self, currentIndex):
  1465. """
  1466. Slot connected to the tabCloseRequested signal
  1467. :param currentIndex:
  1468. :return:
  1469. """
  1470. idx = self.currentIndex()
  1471. self.tab_closed_signal.emit(self.tabText(idx))
  1472. self.removeTab(currentIndex)
  1473. class VerticalScrollArea(QtWidgets.QScrollArea):
  1474. """
  1475. This widget extends QtGui.QScrollArea to make a vertical-only
  1476. scroll area that also expands horizontally to accomodate
  1477. its contents.
  1478. """
  1479. def __init__(self, parent=None):
  1480. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1481. self.setWidgetResizable(True)
  1482. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1483. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1484. def eventFilter(self, source, event):
  1485. """
  1486. The event filter gets automatically installed when setWidget()
  1487. is called.
  1488. :param source:
  1489. :param event:
  1490. :return:
  1491. """
  1492. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1493. # log.debug("VerticalScrollArea: Widget resized:")
  1494. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1495. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1496. self.setMinimumWidth(self.widget().sizeHint().width() +
  1497. self.verticalScrollBar().sizeHint().width())
  1498. # if self.verticalScrollBar().isVisible():
  1499. # log.debug(" Scroll bar visible")
  1500. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1501. # self.verticalScrollBar().width())
  1502. # else:
  1503. # log.debug(" Scroll bar hidden")
  1504. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1505. return QtWidgets.QWidget.eventFilter(self, source, event)
  1506. class OptionalInputSection:
  1507. def __init__(self, cb, optinputs, logic=True):
  1508. """
  1509. Associates the a checkbox with a set of inputs.
  1510. :param cb: Checkbox that enables the optional inputs.
  1511. :param optinputs: List of widgets that are optional.
  1512. :param logic: When True the logic is normal, when False the logic is in reverse
  1513. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1514. for logic=False, when the checkbox is checked the widgets are Disabled
  1515. :return:
  1516. """
  1517. assert isinstance(cb, FCCheckBox), \
  1518. "Expected an FCCheckBox, got %s" % type(cb)
  1519. self.cb = cb
  1520. self.optinputs = optinputs
  1521. self.logic = logic
  1522. self.on_cb_change()
  1523. self.cb.stateChanged.connect(self.on_cb_change)
  1524. def on_cb_change(self):
  1525. if self.cb.checkState():
  1526. for widget in self.optinputs:
  1527. if self.logic is True:
  1528. widget.setEnabled(True)
  1529. else:
  1530. widget.setEnabled(False)
  1531. else:
  1532. for widget in self.optinputs:
  1533. if self.logic is True:
  1534. widget.setEnabled(False)
  1535. else:
  1536. widget.setEnabled(True)
  1537. class OptionalHideInputSection:
  1538. def __init__(self, cb, optinputs, logic=True):
  1539. """
  1540. Associates the a checkbox with a set of inputs.
  1541. :param cb: Checkbox that enables the optional inputs.
  1542. :param optinputs: List of widgets that are optional.
  1543. :param logic: When True the logic is normal, when False the logic is in reverse
  1544. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1545. for logic=False, when the checkbox is checked the widgets are Disabled
  1546. :return:
  1547. """
  1548. assert isinstance(cb, FCCheckBox), \
  1549. "Expected an FCCheckBox, got %s" % type(cb)
  1550. self.cb = cb
  1551. self.optinputs = optinputs
  1552. self.logic = logic
  1553. self.on_cb_change()
  1554. self.cb.stateChanged.connect(self.on_cb_change)
  1555. def on_cb_change(self):
  1556. if self.cb.checkState():
  1557. for widget in self.optinputs:
  1558. if self.logic is True:
  1559. widget.show()
  1560. else:
  1561. widget.hide()
  1562. else:
  1563. for widget in self.optinputs:
  1564. if self.logic is True:
  1565. widget.hide()
  1566. else:
  1567. widget.show()
  1568. class FCTable(QtWidgets.QTableWidget):
  1569. drag_drop_sig = QtCore.pyqtSignal()
  1570. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  1571. super(FCTable, self).__init__(parent)
  1572. if drag_drop:
  1573. self.setDragEnabled(True)
  1574. self.setAcceptDrops(True)
  1575. self.viewport().setAcceptDrops(True)
  1576. self.setDragDropOverwriteMode(False)
  1577. self.setDropIndicatorShown(True)
  1578. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1579. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1580. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  1581. self.rows_not_for_drag_and_drop = list()
  1582. if protected_rows:
  1583. try:
  1584. for r in protected_rows:
  1585. self.rows_not_for_drag_and_drop.append(r)
  1586. except TypeError:
  1587. self.rows_not_for_drag_and_drop = [protected_rows]
  1588. self.rows_to_move = list()
  1589. def sizeHint(self):
  1590. default_hint_size = super(FCTable, self).sizeHint()
  1591. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1592. def getHeight(self):
  1593. height = self.horizontalHeader().height()
  1594. for i in range(self.rowCount()):
  1595. height += self.rowHeight(i)
  1596. return height
  1597. def getWidth(self):
  1598. width = self.verticalHeader().width()
  1599. for i in range(self.columnCount()):
  1600. width += self.columnWidth(i)
  1601. return width
  1602. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  1603. def setColortoRow(self, rowIndex, color):
  1604. for j in range(self.columnCount()):
  1605. self.item(rowIndex, j).setBackground(color)
  1606. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1607. def mousePressEvent(self, event):
  1608. if not self.itemAt(event.pos()):
  1609. self.clearSelection()
  1610. self.clearFocus()
  1611. else:
  1612. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1613. def setupContextMenu(self):
  1614. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1615. def addContextMenu(self, entry, call_function, icon=None):
  1616. action_name = str(entry)
  1617. action = QtWidgets.QAction(self)
  1618. action.setText(action_name)
  1619. if icon:
  1620. assert isinstance(icon, QtGui.QIcon), \
  1621. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1622. action.setIcon(icon)
  1623. self.addAction(action)
  1624. action.triggered.connect(call_function)
  1625. # def dropEvent(self, event: QtGui.QDropEvent):
  1626. # if not event.isAccepted() and event.source() == self:
  1627. # drop_row = self.drop_on(event)
  1628. #
  1629. # rows = sorted(set(item.row() for item in self.selectedItems()))
  1630. # # rows_to_move = [
  1631. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  1632. # # for column_index in range(self.columnCount())] for row_index in rows
  1633. # # ]
  1634. # self.rows_to_move[:] = []
  1635. # for row_index in rows:
  1636. # row_items = list()
  1637. # for column_index in range(self.columnCount()):
  1638. # r_item = self.item(row_index, column_index)
  1639. # w_item = self.cellWidget(row_index, column_index)
  1640. #
  1641. # if r_item is not None:
  1642. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  1643. # elif w_item is not None:
  1644. # row_items.append(w_item)
  1645. #
  1646. # self.rows_to_move.append(row_items)
  1647. #
  1648. # for row_index in reversed(rows):
  1649. # self.removeRow(row_index)
  1650. # if row_index < drop_row:
  1651. # drop_row -= 1
  1652. #
  1653. # for row_index, data in enumerate(self.rows_to_move):
  1654. # row_index += drop_row
  1655. # self.insertRow(row_index)
  1656. #
  1657. # for column_index, column_data in enumerate(data):
  1658. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  1659. # self.setItem(row_index, column_index, column_data)
  1660. # else:
  1661. # self.setCellWidget(row_index, column_index, column_data)
  1662. #
  1663. # event.accept()
  1664. # for row_index in range(len(self.rows_to_move)):
  1665. # self.item(drop_row + row_index, 0).setSelected(True)
  1666. # self.item(drop_row + row_index, 1).setSelected(True)
  1667. #
  1668. # super().dropEvent(event)
  1669. #
  1670. # def drop_on(self, event):
  1671. # ret_val = False
  1672. # index = self.indexAt(event.pos())
  1673. # if not index.isValid():
  1674. # return self.rowCount()
  1675. #
  1676. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  1677. #
  1678. # return ret_val
  1679. #
  1680. # def is_below(self, pos, index):
  1681. # rect = self.visualRect(index)
  1682. # margin = 2
  1683. # if pos.y() - rect.top() < margin:
  1684. # return False
  1685. # elif rect.bottom() - pos.y() < margin:
  1686. # return True
  1687. # # noinspection PyTypeChecker
  1688. # return rect.contains(pos, True) and not (
  1689. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  1690. def dropEvent(self, event):
  1691. """
  1692. From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  1693. :param event:
  1694. :return:
  1695. """
  1696. if event.source() == self:
  1697. rows = set([mi.row() for mi in self.selectedIndexes()])
  1698. # if one of the selected rows for drag and drop is within the protected list, return
  1699. for r in rows:
  1700. if r in self.rows_not_for_drag_and_drop:
  1701. return
  1702. targetRow = self.indexAt(event.pos()).row()
  1703. rows.discard(targetRow)
  1704. rows = sorted(rows)
  1705. if not rows:
  1706. return
  1707. if targetRow == -1:
  1708. targetRow = self.rowCount()
  1709. for _ in range(len(rows)):
  1710. self.insertRow(targetRow)
  1711. rowMapping = dict() # Src row to target row.
  1712. for idx, row in enumerate(rows):
  1713. if row < targetRow:
  1714. rowMapping[row] = targetRow + idx
  1715. else:
  1716. rowMapping[row + len(rows)] = targetRow + idx
  1717. colCount = self.columnCount()
  1718. for srcRow, tgtRow in sorted(rowMapping.items()):
  1719. for col in range(0, colCount):
  1720. new_item = self.item(srcRow, col)
  1721. if new_item is None:
  1722. new_item = self.cellWidget(srcRow, col)
  1723. if isinstance(new_item, QtWidgets.QTableWidgetItem):
  1724. new_item = self.takeItem(srcRow, col)
  1725. self.setItem(tgtRow, col, new_item)
  1726. else:
  1727. self.setCellWidget(tgtRow, col, new_item)
  1728. for row in reversed(sorted(rowMapping.keys())):
  1729. self.removeRow(row)
  1730. event.accept()
  1731. self.drag_drop_sig.emit()
  1732. return
  1733. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1734. def __init__(self, units):
  1735. super(SpinBoxDelegate, self).__init__()
  1736. self.units = units
  1737. self.current_value = None
  1738. def createEditor(self, parent, option, index):
  1739. editor = QtWidgets.QDoubleSpinBox(parent)
  1740. editor.setMinimum(-999.9999)
  1741. editor.setMaximum(999.9999)
  1742. if self.units == 'MM':
  1743. editor.setDecimals(2)
  1744. else:
  1745. editor.setDecimals(3)
  1746. return editor
  1747. def setEditorData(self, spinBox, index):
  1748. try:
  1749. value = float(index.model().data(index, Qt.EditRole))
  1750. except ValueError:
  1751. value = self.current_value
  1752. # return
  1753. spinBox.setValue(value)
  1754. def setModelData(self, spinBox, model, index):
  1755. spinBox.interpretText()
  1756. value = spinBox.value()
  1757. self.current_value = value
  1758. model.setData(index, value, Qt.EditRole)
  1759. def updateEditorGeometry(self, editor, option, index):
  1760. editor.setGeometry(option.rect)
  1761. def setDecimals(self, spinbox, digits):
  1762. spinbox.setDecimals(digits)
  1763. class Dialog_box(QtWidgets.QWidget):
  1764. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  1765. """
  1766. :param title: string with the window title
  1767. :param label: string with the message inside the dialog box
  1768. """
  1769. super(Dialog_box, self).__init__()
  1770. if initial_text is None:
  1771. self.location = str((0, 0))
  1772. else:
  1773. self.location = initial_text
  1774. self.ok = False
  1775. self.dialog_box = QtWidgets.QInputDialog()
  1776. self.dialog_box.setMinimumWidth(290)
  1777. self.setWindowIcon(icon)
  1778. self.location, self.ok = self.dialog_box.getText(self, title, label,
  1779. text=str(self.location).replace('(', '').replace(')', ''))
  1780. self.readyToEdit = True
  1781. def mousePressEvent(self, e, parent=None):
  1782. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1783. if self.readyToEdit:
  1784. self.lineEdit().selectAll()
  1785. self.readyToEdit = False
  1786. def focusOutEvent(self, e):
  1787. # don't focus out if the user requests an popup menu
  1788. if e.reason() != QtCore.Qt.PopupFocusReason:
  1789. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1790. self.lineEdit().deselect()
  1791. self.readyToEdit = True
  1792. class _BrowserTextEdit(QTextEdit):
  1793. def __init__(self, version):
  1794. QTextEdit.__init__(self)
  1795. self.menu = None
  1796. self.version = version
  1797. def contextMenuEvent(self, event):
  1798. self.menu = self.createStandardContextMenu(event.pos())
  1799. clear_action = QAction("Clear", self)
  1800. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1801. self.menu.addAction(clear_action)
  1802. clear_action.triggered.connect(self.clear)
  1803. self.menu.exec_(event.globalPos())
  1804. def clear(self):
  1805. QTextEdit.clear(self)
  1806. text = "FlatCAM %s - Type >help< to get started\n\n" % self.version
  1807. text = html.escape(text)
  1808. text = text.replace('\n', '<br/>')
  1809. self.moveCursor(QTextCursor.End)
  1810. self.insertHtml(text)
  1811. class _ExpandableTextEdit(QTextEdit):
  1812. """
  1813. Class implements edit line, which expands themselves automatically
  1814. """
  1815. historyNext = QtCore.pyqtSignal()
  1816. historyPrev = QtCore.pyqtSignal()
  1817. def __init__(self, termwidget, *args):
  1818. QTextEdit.__init__(self, *args)
  1819. self.setStyleSheet("font: 9pt \"Courier\";")
  1820. self._fittedHeight = 1
  1821. self.textChanged.connect(self._fit_to_document)
  1822. self._fit_to_document()
  1823. self._termWidget = termwidget
  1824. self.completer = MyCompleter()
  1825. self.model = QtCore.QStringListModel()
  1826. self.completer.setModel(self.model)
  1827. self.set_model_data(keyword_list=[])
  1828. self.completer.insertText.connect(self.insertCompletion)
  1829. def set_model_data(self, keyword_list):
  1830. self.model.setStringList(keyword_list)
  1831. def insertCompletion(self, completion):
  1832. tc = self.textCursor()
  1833. extra = (len(completion) - len(self.completer.completionPrefix()))
  1834. # don't insert if the word is finished but add a space instead
  1835. if extra == 0:
  1836. tc.insertText(' ')
  1837. self.completer.popup().hide()
  1838. return
  1839. tc.movePosition(QTextCursor.Left)
  1840. tc.movePosition(QTextCursor.EndOfWord)
  1841. tc.insertText(completion[-extra:])
  1842. # add a space after inserting the word
  1843. tc.insertText(' ')
  1844. self.setTextCursor(tc)
  1845. self.completer.popup().hide()
  1846. def focusInEvent(self, event):
  1847. if self.completer:
  1848. self.completer.setWidget(self)
  1849. QTextEdit.focusInEvent(self, event)
  1850. def keyPressEvent(self, event):
  1851. """
  1852. Catch keyboard events. Process Enter, Up, Down
  1853. """
  1854. key = event.key()
  1855. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1856. self.completer.insertText.emit(self.completer.getSelected())
  1857. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1858. return
  1859. if event.matches(QKeySequence.InsertParagraphSeparator):
  1860. text = self.toPlainText()
  1861. if self._termWidget.is_command_complete(text):
  1862. self._termWidget.exec_current_command()
  1863. return
  1864. elif event.matches(QKeySequence.MoveToNextLine):
  1865. text = self.toPlainText()
  1866. cursor_pos = self.textCursor().position()
  1867. textBeforeEnd = text[cursor_pos:]
  1868. if len(textBeforeEnd.split('\n')) <= 1:
  1869. self.historyNext.emit()
  1870. return
  1871. elif event.matches(QKeySequence.MoveToPreviousLine):
  1872. text = self.toPlainText()
  1873. cursor_pos = self.textCursor().position()
  1874. text_before_start = text[:cursor_pos]
  1875. # lineCount = len(textBeforeStart.splitlines())
  1876. line_count = len(text_before_start.split('\n'))
  1877. if len(text_before_start) > 0 and \
  1878. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1879. line_count += 1
  1880. if line_count <= 1:
  1881. self.historyPrev.emit()
  1882. return
  1883. elif event.matches(QKeySequence.MoveToNextPage) or \
  1884. event.matches(QKeySequence.MoveToPreviousPage):
  1885. return self._termWidget.browser().keyPressEvent(event)
  1886. tc = self.textCursor()
  1887. QTextEdit.keyPressEvent(self, event)
  1888. tc.select(QTextCursor.WordUnderCursor)
  1889. cr = self.cursorRect()
  1890. if len(tc.selectedText()) > 0:
  1891. self.completer.setCompletionPrefix(tc.selectedText())
  1892. popup = self.completer.popup()
  1893. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1894. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1895. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1896. self.completer.complete(cr)
  1897. else:
  1898. self.completer.popup().hide()
  1899. def sizeHint(self):
  1900. """
  1901. QWidget sizeHint impelemtation
  1902. """
  1903. hint = QTextEdit.sizeHint(self)
  1904. hint.setHeight(self._fittedHeight)
  1905. return hint
  1906. def _fit_to_document(self):
  1907. """
  1908. Update widget height to fit all text
  1909. """
  1910. documentsize = self.document().size().toSize()
  1911. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1912. self.setMaximumHeight(self._fittedHeight)
  1913. self.updateGeometry()
  1914. def insertFromMimeData(self, mime_data):
  1915. # Paste only plain text.
  1916. self.insertPlainText(mime_data.text())
  1917. class MyCompleter(QCompleter):
  1918. insertText = QtCore.pyqtSignal(str)
  1919. def __init__(self, parent=None):
  1920. QCompleter.__init__(self)
  1921. self.setCompletionMode(QCompleter.PopupCompletion)
  1922. self.highlighted.connect(self.setHighlighted)
  1923. # self.popup().installEventFilter(self)
  1924. # def eventFilter(self, obj, event):
  1925. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  1926. # pass
  1927. # return False
  1928. def setHighlighted(self, text):
  1929. self.lastSelected = text
  1930. def getSelected(self):
  1931. return self.lastSelected
  1932. class FCTextAreaLineNumber(QtWidgets.QFrame):
  1933. textChanged = QtCore.pyqtSignal()
  1934. class NumberBar(QtWidgets.QWidget):
  1935. def __init__(self, edit):
  1936. QtWidgets.QWidget.__init__(self, edit)
  1937. self.edit = edit
  1938. self.adjustWidth(1)
  1939. def paintEvent(self, event):
  1940. self.edit.numberbarPaint(self, event)
  1941. QtWidgets.QWidget.paintEvent(self, event)
  1942. def adjustWidth(self, count):
  1943. # three spaces added to the width to make up for the space added in the line number
  1944. width = self.fontMetrics().width(str(count) + ' ')
  1945. if self.width() != width:
  1946. self.setFixedWidth(width)
  1947. def updateContents(self, rect, scroll):
  1948. if scroll:
  1949. self.scroll(0, scroll)
  1950. else:
  1951. # It would be nice to do
  1952. # self.update(0, rect.y(), self.width(), rect.height())
  1953. # But we can't because it will not remove the bold on the
  1954. # current line if word wrap is enabled and a new block is
  1955. # selected.
  1956. self.update()
  1957. class PlainTextEdit(FCPlainTextAreaExtended):
  1958. """
  1959. TextEdit with line numbers and highlight
  1960. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  1961. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  1962. """
  1963. def __init__(self, *args):
  1964. FCPlainTextAreaExtended.__init__(self, *args)
  1965. # self.setFrameStyle(QFrame.NoFrame)
  1966. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  1967. self.highlight()
  1968. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  1969. self.cursorPositionChanged.connect(self.highlight)
  1970. def highlight(self):
  1971. hi_selection = QTextEdit.ExtraSelection()
  1972. hi_selection.format.setBackground(self.palette().alternateBase())
  1973. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  1974. hi_selection.cursor = self.textCursor()
  1975. hi_selection.cursor.clearSelection()
  1976. self.setExtraSelections([hi_selection])
  1977. def numberbarPaint(self, number_bar, event):
  1978. font_metrics = self.fontMetrics()
  1979. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  1980. painter = QtGui.QPainter(number_bar)
  1981. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  1982. block = self.firstVisibleBlock()
  1983. line_count = int(block.blockNumber())
  1984. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  1985. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  1986. # Iterate over all visible text blocks in the document.
  1987. while block.isValid() and block_top <= event.rect().bottom():
  1988. line_count += 1
  1989. # Check if the position of the block is out side of the visible
  1990. # area.
  1991. if block.isVisible() and block_bottom >= event.rect().top():
  1992. # We want the line number for the selected line to be bold.
  1993. if line_count == current_line:
  1994. font = painter.font()
  1995. font.setBold(True)
  1996. painter.setPen(QtCore.Qt.blue)
  1997. painter.setFont(font)
  1998. else:
  1999. font = painter.font()
  2000. font.setBold(False)
  2001. painter.setPen(self.palette().base().color())
  2002. painter.setFont(font)
  2003. # Draw the line number right justified at the position of the line.
  2004. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  2005. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  2006. # NumberBar() class above
  2007. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  2008. block = block.next()
  2009. block_top = block_bottom
  2010. block_bottom = block_top + self.blockBoundingRect(block).height()
  2011. painter.end()
  2012. def __init__(self, *args):
  2013. QtWidgets.QFrame.__init__(self, *args)
  2014. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  2015. self.edit = self.PlainTextEdit()
  2016. self.number_bar = self.NumberBar(self.edit)
  2017. hbox = QtWidgets.QHBoxLayout(self)
  2018. hbox.setSpacing(0)
  2019. hbox.setContentsMargins(0, 0, 0, 0)
  2020. hbox.addWidget(self.number_bar)
  2021. hbox.addWidget(self.edit)
  2022. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  2023. self.edit.updateRequest.connect(self.number_bar.updateContents)
  2024. def getText(self):
  2025. return str(self.edit.toPlainText())
  2026. def setText(self, text):
  2027. self.edit.setPlainText(text)
  2028. def isModified(self):
  2029. return self.edit.document().isModified()
  2030. def setModified(self, modified):
  2031. self.edit.document().setModified(modified)
  2032. def setLineWrapMode(self, mode):
  2033. self.edit.setLineWrapMode(mode)
  2034. def rreplace(s, old, new, occurrence):
  2035. """
  2036. Credits go here:
  2037. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  2038. :param s: string to be processed
  2039. :param old: old char to be replaced
  2040. :param new: new char to replace the old one
  2041. :param occurrence: how many places from end to replace the old char
  2042. :return: modified string
  2043. """
  2044. li = s.rsplit(old, occurrence)
  2045. return new.join(li)