GUIElements.py 88 KB

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