GUIElements.py 74 KB

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