GUIElements.py 91 KB

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