GUIElements.py 67 KB

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