GUIElements.py 91 KB

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