GUIElements.py 68 KB

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