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 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. 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 keyPressEvent(self, in_event): # 46 = dot; 44 = comma:
  479. # if in_event.key() == 44:
  480. # print(in_event, "ahaaa")
  481. # event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, 46, Qt.NoModifier, 0, 0, 0)
  482. # QtWidgets.QApplication.sendEvent(self.parent(), event)
  483. # else:
  484. # super().keyPressEvent(in_event)
  485. def focusOutEvent(self, e):
  486. # don't focus out if the user requests an popup menu
  487. if e.reason() != QtCore.Qt.PopupFocusReason:
  488. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  489. self.lineEdit().deselect()
  490. self.readyToEdit = True
  491. def get_value(self):
  492. return float(self.value())
  493. def set_value(self, val):
  494. try:
  495. k = float(val)
  496. except Exception as e:
  497. log.debug(str(e))
  498. return
  499. self.setValue(k)
  500. def set_precision(self, val):
  501. self.setDecimals(val)
  502. def set_range(self, min_val, max_val):
  503. self.setRange(min_val, max_val)
  504. class FCCheckBox(QtWidgets.QCheckBox):
  505. def __init__(self, label='', parent=None):
  506. super(FCCheckBox, self).__init__(str(label), parent)
  507. def get_value(self):
  508. return self.isChecked()
  509. def set_value(self, val):
  510. self.setChecked(val)
  511. def toggle(self):
  512. self.set_value(not self.get_value())
  513. class FCTextArea(QtWidgets.QPlainTextEdit):
  514. def __init__(self, parent=None):
  515. super(FCTextArea, self).__init__(parent)
  516. def set_value(self, val):
  517. self.setPlainText(val)
  518. def get_value(self):
  519. return str(self.toPlainText())
  520. def sizeHint(self, custom_sizehint=None):
  521. default_hint_size = super(FCTextArea, self).sizeHint()
  522. if custom_sizehint is None:
  523. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  524. else:
  525. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  526. class FCTextAreaRich(QtWidgets.QTextEdit):
  527. def __init__(self, parent=None):
  528. super(FCTextAreaRich, self).__init__(parent)
  529. def set_value(self, val):
  530. self.setText(val)
  531. def get_value(self):
  532. return str(self.toPlainText())
  533. def sizeHint(self):
  534. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  535. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  536. class FCTextAreaExtended(QtWidgets.QTextEdit):
  537. def __init__(self, parent=None):
  538. super().__init__(parent)
  539. self.completer = MyCompleter()
  540. self.model = QtCore.QStringListModel()
  541. self.completer.setModel(self.model)
  542. self.set_model_data(keyword_list=[])
  543. self.completer.insertText.connect(self.insertCompletion)
  544. self.completer_enable = False
  545. def set_model_data(self, keyword_list):
  546. self.model.setStringList(keyword_list)
  547. def insertCompletion(self, completion):
  548. tc = self.textCursor()
  549. extra = (len(completion) - len(self.completer.completionPrefix()))
  550. # don't insert if the word is finished but add a space instead
  551. if extra == 0:
  552. tc.insertText(' ')
  553. self.completer.popup().hide()
  554. return
  555. tc.movePosition(QTextCursor.Left)
  556. tc.movePosition(QTextCursor.EndOfWord)
  557. tc.insertText(completion[-extra:])
  558. # add a space after inserting the word
  559. tc.insertText(' ')
  560. self.setTextCursor(tc)
  561. self.completer.popup().hide()
  562. def focusInEvent(self, event):
  563. if self.completer:
  564. self.completer.setWidget(self)
  565. QTextEdit.focusInEvent(self, event)
  566. def set_value(self, val):
  567. self.setText(val)
  568. def get_value(self):
  569. self.toPlainText()
  570. def insertFromMimeData(self, data):
  571. """
  572. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  573. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  574. :param data:
  575. :return:
  576. """
  577. modifier = QtWidgets.QApplication.keyboardModifiers()
  578. if modifier == Qt.ShiftModifier:
  579. text = data.text()
  580. text = text.replace('\\', '/')
  581. self.insertPlainText(text)
  582. else:
  583. self.insertPlainText(data.text())
  584. def keyPressEvent(self, event):
  585. """
  586. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  587. :param event:
  588. :return:
  589. """
  590. key = event.key()
  591. modifier = QtWidgets.QApplication.keyboardModifiers()
  592. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  593. if key == QtCore.Qt.Key_V:
  594. clipboard = QtWidgets.QApplication.clipboard()
  595. clip_text = clipboard.text()
  596. clip_text = clip_text.replace('\\', '/')
  597. self.insertPlainText(clip_text)
  598. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  599. self.comment()
  600. tc = self.textCursor()
  601. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  602. self.completer.insertText.emit(self.completer.getSelected())
  603. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  604. return
  605. elif key == Qt.Key_BraceLeft:
  606. tc.insertText('{}')
  607. self.moveCursor(QtGui.QTextCursor.Left)
  608. elif key == Qt.Key_BracketLeft:
  609. tc.insertText('[]')
  610. self.moveCursor(QtGui.QTextCursor.Left)
  611. elif key == Qt.Key_ParenLeft:
  612. tc.insertText('()')
  613. self.moveCursor(QtGui.QTextCursor.Left)
  614. elif key == Qt.Key_BraceRight:
  615. tc.select(QtGui.QTextCursor.WordUnderCursor)
  616. if tc.selectedText() == '}':
  617. tc.movePosition(QTextCursor.Right)
  618. self.setTextCursor(tc)
  619. else:
  620. tc.clearSelection()
  621. self.textCursor().insertText('}')
  622. elif key == Qt.Key_BracketRight:
  623. tc.select(QtGui.QTextCursor.WordUnderCursor)
  624. if tc.selectedText() == ']':
  625. tc.movePosition(QTextCursor.Right)
  626. self.setTextCursor(tc)
  627. else:
  628. tc.clearSelection()
  629. self.textCursor().insertText(']')
  630. elif key == Qt.Key_ParenRight:
  631. tc.select(QtGui.QTextCursor.WordUnderCursor)
  632. if tc.selectedText() == ')':
  633. tc.movePosition(QTextCursor.Right)
  634. self.setTextCursor(tc)
  635. else:
  636. tc.clearSelection()
  637. self.textCursor().insertText(')')
  638. else:
  639. super(FCTextAreaExtended, self).keyPressEvent(event)
  640. if self.completer_enable:
  641. tc.select(QTextCursor.WordUnderCursor)
  642. cr = self.cursorRect()
  643. if len(tc.selectedText()) > 0:
  644. self.completer.setCompletionPrefix(tc.selectedText())
  645. popup = self.completer.popup()
  646. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  647. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  648. + self.completer.popup().verticalScrollBar().sizeHint().width())
  649. self.completer.complete(cr)
  650. else:
  651. self.completer.popup().hide()
  652. def comment(self):
  653. """
  654. Got it from here:
  655. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  656. :return:
  657. """
  658. pos = self.textCursor().position()
  659. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  660. line_text = self.textCursor().block().text()
  661. if self.textCursor().block().text().startswith(" "):
  662. # skip the white space
  663. self.moveCursor(QtGui.QTextCursor.NextWord)
  664. self.moveCursor(QtGui.QTextCursor.NextCharacter,QtGui.QTextCursor.KeepAnchor)
  665. character = self.textCursor().selectedText()
  666. if character == "#":
  667. # delete #
  668. self.textCursor().deletePreviousChar()
  669. # delete white space
  670. self.moveCursor(QtGui.QTextCursor.NextWord,QtGui.QTextCursor.KeepAnchor)
  671. self.textCursor().removeSelectedText()
  672. else:
  673. self.moveCursor(QtGui.QTextCursor.PreviousCharacter,QtGui.QTextCursor.KeepAnchor)
  674. self.textCursor().insertText("# ")
  675. cursor = QtGui.QTextCursor(self.textCursor())
  676. cursor.setPosition(pos)
  677. self.setTextCursor(cursor)
  678. class FCComboBox(QtWidgets.QComboBox):
  679. def __init__(self, parent=None, callback=None):
  680. super(FCComboBox, self).__init__(parent)
  681. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  682. self.view = self.view()
  683. self.view.viewport().installEventFilter(self)
  684. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  685. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  686. # pos = mouse right click click position
  687. # self = is the combobox object itself
  688. if callback:
  689. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  690. def eventFilter(self, obj, event):
  691. if event.type() == QtCore.QEvent.MouseButtonRelease:
  692. if event.button() == Qt.RightButton:
  693. return True
  694. return False
  695. def wheelEvent(self, *args, **kwargs):
  696. pass
  697. def get_value(self):
  698. return str(self.currentText())
  699. def set_value(self, val):
  700. self.setCurrentIndex(self.findText(str(val)))
  701. class FCInputDialog(QtWidgets.QInputDialog):
  702. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  703. init_val=None):
  704. super(FCInputDialog, self).__init__(parent)
  705. self.allow_empty = ok
  706. self.empty_val = val
  707. self.val = 0.0
  708. self.ok = ''
  709. self.init_value = init_val if init_val else 0.0
  710. if title is None:
  711. self.title = 'title'
  712. else:
  713. self.title = title
  714. if text is None:
  715. self.text = 'text'
  716. else:
  717. self.text = text
  718. if min is None:
  719. self.min = 0
  720. else:
  721. self.min = min
  722. if max is None:
  723. self.max = 0
  724. else:
  725. self.max = max
  726. if decimals is None:
  727. self.decimals = 6
  728. else:
  729. self.decimals = decimals
  730. def get_value(self):
  731. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  732. max=self.max, decimals=self.decimals, value=self.init_value)
  733. return [self.val, self.ok]
  734. # "Transform", "Enter the Angle value:"
  735. def set_value(self, val):
  736. pass
  737. class FCButton(QtWidgets.QPushButton):
  738. def __init__(self, parent=None):
  739. super(FCButton, self).__init__(parent)
  740. def get_value(self):
  741. return self.isChecked()
  742. def set_value(self, val):
  743. self.setText(str(val))
  744. class FCMenu(QtWidgets.QMenu):
  745. def __init__(self):
  746. super().__init__()
  747. self.mouse_is_panning = False
  748. def popup(self, pos, action=None):
  749. self.mouse_is_panning = False
  750. super().popup(pos)
  751. class FCTab(QtWidgets.QTabWidget):
  752. def __init__(self, parent=None):
  753. super(FCTab, self).__init__(parent)
  754. self.setTabsClosable(True)
  755. self.tabCloseRequested.connect(self.closeTab)
  756. def deleteTab(self, currentIndex):
  757. widget = self.widget(currentIndex)
  758. if widget is not None:
  759. widget.deleteLater()
  760. self.removeTab(currentIndex)
  761. def closeTab(self, currentIndex):
  762. self.removeTab(currentIndex)
  763. def protectTab(self, currentIndex):
  764. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  765. # class FCTabBar(QtWidgets.QTabBar):
  766. # def tabSizeHint(self, index):
  767. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  768. # w = int(self.width()/self.count())
  769. # return QtCore.QSize(w, size.height())
  770. class FCDetachableTab(QtWidgets.QTabWidget):
  771. """
  772. From here:
  773. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  774. """
  775. def __init__(self, protect=None, protect_by_name=None, parent=None):
  776. super().__init__()
  777. self.tabBar = self.FCTabBar(self)
  778. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  779. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  780. self.set_detachable(val=True)
  781. self.setTabBar(self.tabBar)
  782. # Used to keep a reference to detached tabs since their QMainWindow
  783. # does not have a parent
  784. self.detachedTabs = {}
  785. # a way to make sure that tabs can't be closed after they attach to the parent tab
  786. self.protect_tab = True if protect is not None and protect is True else False
  787. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  788. # Close all detached tabs if the application is closed explicitly
  789. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  790. # used by the property self.useOldIndex(param)
  791. self.use_old_index = None
  792. self.old_index = None
  793. self.setTabsClosable(True)
  794. self.tabCloseRequested.connect(self.closeTab)
  795. def set_rmb_callback(self, callback):
  796. """
  797. :param callback: Function to call on right mouse click on tab
  798. :type callback: func
  799. :return: None
  800. """
  801. self.tabBar.right_click.connect(callback)
  802. def set_detachable(self, val=True):
  803. try:
  804. self.tabBar.onDetachTabSignal.disconnect()
  805. except TypeError:
  806. pass
  807. if val is True:
  808. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  809. # the tab can be moved around
  810. self.tabBar.can_be_dragged = True
  811. else:
  812. # the detached tab can't be moved
  813. self.tabBar.can_be_dragged = False
  814. return val
  815. def setupContextMenu(self):
  816. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  817. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  818. action_name = str(entry)
  819. action = QtWidgets.QAction(self)
  820. action.setCheckable(True)
  821. action.setText(action_name)
  822. if icon:
  823. assert isinstance(icon, QtGui.QIcon), \
  824. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  825. action.setIcon(icon)
  826. action.setChecked(initial_checked)
  827. self.addAction(action)
  828. action.triggered.connect(call_function)
  829. def useOldIndex(self, param):
  830. if param:
  831. self.use_old_index = True
  832. else:
  833. self.use_old_index = False
  834. def deleteTab(self, currentIndex):
  835. widget = self.widget(currentIndex)
  836. if widget is not None:
  837. widget.deleteLater()
  838. self.removeTab(currentIndex)
  839. def closeTab(self, currentIndex):
  840. """
  841. Slot connected to the tabCloseRequested signal
  842. :param currentIndex:
  843. :return:
  844. """
  845. self.removeTab(currentIndex)
  846. def protectTab(self, currentIndex):
  847. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  848. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  849. def setMovable(self, movable):
  850. """
  851. The default movable functionality of QTabWidget must remain disabled
  852. so as not to conflict with the added features
  853. :param movable:
  854. :return:
  855. """
  856. pass
  857. @pyqtSlot(int, int)
  858. def moveTab(self, fromIndex, toIndex):
  859. """
  860. Move a tab from one position (index) to another
  861. :param fromIndex: the original index location of the tab
  862. :param toIndex: the new index location of the tab
  863. :return:
  864. """
  865. widget = self.widget(fromIndex)
  866. icon = self.tabIcon(fromIndex)
  867. text = self.tabText(fromIndex)
  868. self.removeTab(fromIndex)
  869. self.insertTab(toIndex, widget, icon, text)
  870. self.setCurrentIndex(toIndex)
  871. @pyqtSlot(int, QtCore.QPoint)
  872. def detachTab(self, index, point):
  873. """
  874. Detach the tab by removing it's contents and placing them in
  875. a DetachedTab window
  876. :param index: the index location of the tab to be detached
  877. :param point: the screen position for creating the new DetachedTab window
  878. :return:
  879. """
  880. self.old_index = index
  881. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  882. name = "FlatCAM " + self.tabText(index)
  883. icon = self.tabIcon(index)
  884. if icon.isNull():
  885. icon = self.window().windowIcon()
  886. contentWidget = self.widget(index)
  887. try:
  888. contentWidgetRect = contentWidget.frameGeometry()
  889. except AttributeError:
  890. return
  891. # Create a new detached tab window
  892. detachedTab = self.FCDetachedTab(name, contentWidget)
  893. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  894. detachedTab.setWindowIcon(icon)
  895. detachedTab.setGeometry(contentWidgetRect)
  896. detachedTab.onCloseSignal.connect(self.attachTab)
  897. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  898. detachedTab.move(point)
  899. detachedTab.show()
  900. # Create a reference to maintain access to the detached tab
  901. self.detachedTabs[name] = detachedTab
  902. def attachTab(self, contentWidget, name, icon, insertAt=None):
  903. """
  904. Re-attach the tab by removing the content from the DetachedTab window,
  905. closing it, and placing the content back into the DetachableTabWidget
  906. :param contentWidget: the content widget from the DetachedTab window
  907. :param name: the name of the detached tab
  908. :param icon: the window icon for the detached tab
  909. :param insertAt: insert the re-attached tab at the given index
  910. :return:
  911. """
  912. # Make the content widget a child of this widget
  913. contentWidget.setParent(self)
  914. # Remove the reference
  915. del self.detachedTabs[name]
  916. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  917. name = name.partition(' ')[2]
  918. # helps in restoring the tab to the same index that it was before was detached
  919. insert_index = self.old_index if self.use_old_index is True else insertAt
  920. # Create an image from the given icon (for comparison)
  921. if not icon.isNull():
  922. try:
  923. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  924. tabIconImage = tabIconPixmap.toImage()
  925. except IndexError:
  926. tabIconImage = None
  927. else:
  928. tabIconImage = None
  929. # Create an image of the main window icon (for comparison)
  930. if not icon.isNull():
  931. try:
  932. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  933. windowIconImage = windowIconPixmap.toImage()
  934. except IndexError:
  935. windowIconImage = None
  936. else:
  937. windowIconImage = None
  938. # Determine if the given image and the main window icon are the same.
  939. # If they are, then do not add the icon to the tab
  940. if tabIconImage == windowIconImage:
  941. if insert_index is None:
  942. index = self.addTab(contentWidget, name)
  943. else:
  944. index = self.insertTab(insert_index, contentWidget, name)
  945. else:
  946. if insert_index is None:
  947. index = self.addTab(contentWidget, icon, name)
  948. else:
  949. index = self.insertTab(insert_index, contentWidget, icon, name)
  950. # on reattaching the tab if protect is true then the closure button is not added
  951. if self.protect_tab is True:
  952. self.protectTab(index)
  953. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  954. if self.protect_by_name is not None:
  955. for tab_name in self.protect_by_name:
  956. for index in range(self.count()):
  957. if str(tab_name) == str(self.tabText(index)):
  958. self.protectTab(index)
  959. # Make this tab the current tab
  960. if index > -1:
  961. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  962. def removeTabByName(self, name):
  963. """
  964. Remove the tab with the given name, even if it is detached
  965. :param name: the name of the tab to be removed
  966. :return:
  967. """
  968. # Remove the tab if it is attached
  969. attached = False
  970. for index in range(self.count()):
  971. if str(name) == str(self.tabText(index)):
  972. self.removeTab(index)
  973. attached = True
  974. break
  975. # If the tab is not attached, close it's window and
  976. # remove the reference to it
  977. if not attached:
  978. for key in self.detachedTabs:
  979. if str(name) == str(key):
  980. self.detachedTabs[key].onCloseSignal.disconnect()
  981. self.detachedTabs[key].close()
  982. del self.detachedTabs[key]
  983. break
  984. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  985. def detachedTabDrop(self, name, index, dropPos):
  986. """
  987. Handle dropping of a detached tab inside the DetachableTabWidget
  988. :param name: the name of the detached tab
  989. :param index: the index of an existing tab (if the tab bar
  990. # determined that the drop occurred on an
  991. # existing tab)
  992. :param dropPos: the mouse cursor position when the drop occurred
  993. :return:
  994. """
  995. # If the drop occurred on an existing tab, insert the detached
  996. # tab at the existing tab's location
  997. if index > -1:
  998. # Create references to the detached tab's content and icon
  999. contentWidget = self.detachedTabs[name].contentWidget
  1000. icon = self.detachedTabs[name].windowIcon()
  1001. # Disconnect the detached tab's onCloseSignal so that it
  1002. # does not try to re-attach automatically
  1003. self.detachedTabs[name].onCloseSignal.disconnect()
  1004. # Close the detached
  1005. self.detachedTabs[name].close()
  1006. # Re-attach the tab at the given index
  1007. self.attachTab(contentWidget, name, icon, index)
  1008. # If the drop did not occur on an existing tab, determine if the drop
  1009. # occurred in the tab bar area (the area to the side of the QTabBar)
  1010. else:
  1011. # Find the drop position relative to the DetachableTabWidget
  1012. tabDropPos = self.mapFromGlobal(dropPos)
  1013. # If the drop position is inside the DetachableTabWidget...
  1014. if self.rect().contains(tabDropPos):
  1015. # If the drop position is inside the tab bar area (the
  1016. # area to the side of the QTabBar) or there are not tabs
  1017. # currently attached...
  1018. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1019. # Close the detached tab and allow it to re-attach
  1020. # automatically
  1021. self.detachedTabs[name].close()
  1022. def closeDetachedTabs(self):
  1023. """
  1024. Close all tabs that are currently detached.
  1025. :return:
  1026. """
  1027. listOfDetachedTabs = []
  1028. for key in self.detachedTabs:
  1029. listOfDetachedTabs.append(self.detachedTabs[key])
  1030. for detachedTab in listOfDetachedTabs:
  1031. detachedTab.close()
  1032. class FCDetachedTab(QtWidgets.QMainWindow):
  1033. """
  1034. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1035. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1036. """
  1037. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1038. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  1039. def __init__(self, name, contentWidget):
  1040. QtWidgets.QMainWindow.__init__(self, None)
  1041. self.setObjectName(name)
  1042. self.setWindowTitle(name)
  1043. self.contentWidget = contentWidget
  1044. self.setCentralWidget(self.contentWidget)
  1045. self.contentWidget.show()
  1046. self.windowDropFilter = self.WindowDropFilter()
  1047. self.installEventFilter(self.windowDropFilter)
  1048. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1049. @QtCore.pyqtSlot(QtCore.QPoint)
  1050. def windowDropSlot(self, dropPos):
  1051. """
  1052. Handle a window drop event
  1053. :param dropPos: the mouse cursor position of the drop
  1054. :return:
  1055. """
  1056. self.onDropSignal.emit(self.objectName(), dropPos)
  1057. def closeEvent(self, event):
  1058. """
  1059. If the window is closed, emit the onCloseSignal and give the
  1060. content widget back to the DetachableTabWidget
  1061. :param event: a close event
  1062. :return:
  1063. """
  1064. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1065. class WindowDropFilter(QtCore.QObject):
  1066. """
  1067. An event filter class to detect a QMainWindow drop event
  1068. """
  1069. onDropSignal = pyqtSignal(QtCore.QPoint)
  1070. def __init__(self):
  1071. QtCore.QObject.__init__(self)
  1072. self.lastEvent = None
  1073. def eventFilter(self, obj, event):
  1074. """
  1075. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1076. event that immediately follows a Move event
  1077. :param obj: the object that generated the event
  1078. :param event: the current event
  1079. :return:
  1080. """
  1081. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1082. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1083. # Determine the position of the mouse cursor and emit it with the
  1084. # onDropSignal
  1085. mouseCursor = QtGui.QCursor()
  1086. dropPos = mouseCursor.pos()
  1087. self.onDropSignal.emit(dropPos)
  1088. self.lastEvent = event.type()
  1089. return True
  1090. else:
  1091. self.lastEvent = event.type()
  1092. return False
  1093. class FCTabBar(QtWidgets.QTabBar):
  1094. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  1095. onMoveTabSignal = pyqtSignal(int, int)
  1096. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  1097. right_click = pyqtSignal(int)
  1098. def __init__(self, parent=None):
  1099. QtWidgets.QTabBar.__init__(self, parent)
  1100. self.setAcceptDrops(True)
  1101. self.setElideMode(QtCore.Qt.ElideRight)
  1102. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1103. self.prev_index = -1
  1104. self.dragStartPos = QtCore.QPoint()
  1105. self.dragDropedPos = QtCore.QPoint()
  1106. self.mouseCursor = QtGui.QCursor()
  1107. self.dragInitiated = False
  1108. # set this to False and the tab will no longer be displayed as detached
  1109. self.can_be_dragged = True
  1110. def mouseDoubleClickEvent(self, event):
  1111. """
  1112. Send the onDetachTabSignal when a tab is double clicked
  1113. :param event: a mouse double click event
  1114. :return:
  1115. """
  1116. event.accept()
  1117. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1118. def mousePressEvent(self, event):
  1119. """
  1120. Set the starting position for a drag event when the left mouse button is pressed.
  1121. Start detection of a right mouse click.
  1122. :param event: a mouse press event
  1123. :return:
  1124. """
  1125. if event.button() == QtCore.Qt.LeftButton:
  1126. self.dragStartPos = event.pos()
  1127. elif event.button() == QtCore.Qt.RightButton:
  1128. self.prev_index = self.tabAt(event.pos())
  1129. self.dragDropedPos.setX(0)
  1130. self.dragDropedPos.setY(0)
  1131. self.dragInitiated = False
  1132. QtWidgets.QTabBar.mousePressEvent(self, event)
  1133. def mouseReleaseEvent(self, event):
  1134. """
  1135. Finish the detection of the right mouse click on the tab
  1136. :param event: a mouse press event
  1137. :return:
  1138. """
  1139. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1140. self.right_click.emit(self.prev_index)
  1141. self.prev_index = -1
  1142. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1143. def mouseMoveEvent(self, event):
  1144. """
  1145. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1146. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1147. bar, emit an onDetachTabSignal.
  1148. :param event: a mouse move event
  1149. :return:
  1150. """
  1151. # Determine if the current movement is detected as a drag
  1152. if not self.dragStartPos.isNull() and \
  1153. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1154. self.dragInitiated = True
  1155. # If the current movement is a drag initiated by the left button
  1156. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated and self.can_be_dragged):
  1157. # Stop the move event
  1158. finishMoveEvent = QtGui.QMouseEvent(
  1159. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1160. )
  1161. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1162. # Convert the move event into a drag
  1163. drag = QtGui.QDrag(self)
  1164. mimeData = QtCore.QMimeData()
  1165. # mimeData.setData('action', 'application/tab-detach')
  1166. drag.setMimeData(mimeData)
  1167. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1168. # Create the appearance of dragging the tab content
  1169. try:
  1170. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1171. except Exception as e:
  1172. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1173. return
  1174. targetPixmap = QtGui.QPixmap(pixmap.size())
  1175. targetPixmap.fill(QtCore.Qt.transparent)
  1176. painter = QtGui.QPainter(targetPixmap)
  1177. painter.setOpacity(0.85)
  1178. painter.drawPixmap(0, 0, pixmap)
  1179. painter.end()
  1180. drag.setPixmap(targetPixmap)
  1181. # Initiate the drag
  1182. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1183. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1184. # must be set manually
  1185. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1186. dropAction = QtCore.Qt.MoveAction
  1187. # If the drag completed outside of the tab bar, detach the tab and move
  1188. # the content to the current cursor position
  1189. if dropAction == QtCore.Qt.IgnoreAction:
  1190. event.accept()
  1191. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1192. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1193. elif dropAction == QtCore.Qt.MoveAction:
  1194. if not self.dragDropedPos.isNull():
  1195. event.accept()
  1196. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1197. else:
  1198. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1199. def dragEnterEvent(self, event):
  1200. """
  1201. Determine if the drag has entered a tab position from another tab position
  1202. :param event: a drag enter event
  1203. :return:
  1204. """
  1205. mimeData = event.mimeData()
  1206. # formats = mcd imeData.formats()
  1207. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1208. # event.acceptProposedAction()
  1209. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1210. def dropEvent(self, event):
  1211. """
  1212. Get the position of the end of the drag
  1213. :param event: a drop event
  1214. :return:
  1215. """
  1216. self.dragDropedPos = event.pos()
  1217. QtWidgets.QTabBar.dropEvent(self, event)
  1218. def detachedTabDrop(self, name, dropPos):
  1219. """
  1220. Determine if the detached tab drop event occurred on an existing tab,
  1221. then send the event to the DetachableTabWidget
  1222. :param name:
  1223. :param dropPos:
  1224. :return:
  1225. """
  1226. tabDropPos = self.mapFromGlobal(dropPos)
  1227. index = self.tabAt(tabDropPos)
  1228. self.detachedTabDropSignal.emit(name, index, dropPos)
  1229. class FCDetachableTab2(FCDetachableTab):
  1230. tab_closed_signal = pyqtSignal(object)
  1231. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1232. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1233. def closeTab(self, currentIndex):
  1234. """
  1235. Slot connected to the tabCloseRequested signal
  1236. :param currentIndex:
  1237. :return:
  1238. """
  1239. idx = self.currentIndex()
  1240. self.tab_closed_signal.emit(self.tabText(idx))
  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