GUIElements.py 67 KB

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