GUIElements.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot
  3. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  4. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  5. from copy import copy
  6. import re
  7. import logging
  8. import html
  9. log = logging.getLogger('base')
  10. EDIT_SIZE_HINT = 70
  11. class RadioSet(QtWidgets.QWidget):
  12. activated_custom = QtCore.pyqtSignal()
  13. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  14. """
  15. The choices are specified as a list of dictionaries containing:
  16. * 'label': Shown in the UI
  17. * 'value': The value returned is selected
  18. :param choices: List of choices. See description.
  19. :param orientation: 'horizontal' (default) of 'vertical'.
  20. :param parent: Qt parent widget.
  21. :type choices: list
  22. """
  23. super(RadioSet, self).__init__(parent)
  24. self.choices = copy(choices)
  25. if orientation == 'horizontal':
  26. layout = QtWidgets.QHBoxLayout()
  27. else:
  28. layout = QtWidgets.QVBoxLayout()
  29. group = QtWidgets.QButtonGroup(self)
  30. for choice in self.choices:
  31. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  32. group.addButton(choice['radio'])
  33. layout.addWidget(choice['radio'], stretch=0)
  34. choice['radio'].toggled.connect(self.on_toggle)
  35. layout.setContentsMargins(0, 0, 0, 0)
  36. if stretch is False:
  37. pass
  38. else:
  39. layout.addStretch()
  40. self.setLayout(layout)
  41. self.group_toggle_fn = lambda: None
  42. def on_toggle(self):
  43. # log.debug("Radio toggled")
  44. radio = self.sender()
  45. if radio.isChecked():
  46. self.group_toggle_fn()
  47. self.activated_custom.emit()
  48. return
  49. def get_value(self):
  50. for choice in self.choices:
  51. if choice['radio'].isChecked():
  52. return choice['value']
  53. log.error("No button was toggled in RadioSet.")
  54. return None
  55. def set_value(self, val):
  56. for choice in self.choices:
  57. if choice['value'] == val:
  58. choice['radio'].setChecked(True)
  59. return
  60. log.error("Value given is not part of this RadioSet: %s" % str(val))
  61. # class RadioGroupChoice(QtWidgets.QWidget):
  62. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  63. # """
  64. # The choices are specified as a list of dictionaries containing:
  65. #
  66. # * 'label': Shown in the UI
  67. # * 'value': The value returned is selected
  68. #
  69. # :param choices: List of choices. See description.
  70. # :param orientation: 'horizontal' (default) of 'vertical'.
  71. # :param parent: Qt parent widget.
  72. # :type choices: list
  73. # """
  74. # super().__init__(parent)
  75. #
  76. # group = QtGui.QButtonGroup(self)
  77. #
  78. # self.lbl1 = label_1
  79. # self.lbl2 = label_2
  80. # self.hide_list = hide_list
  81. # self.show_list = show_list
  82. #
  83. # self.btn1 = QtGui.QRadioButton(str(label_1))
  84. # self.btn2 = QtGui.QRadioButton(str(label_2))
  85. # group.addButton(self.btn1)
  86. # group.addButton(self.btn2)
  87. #
  88. # if to_check == 1:
  89. # self.btn1.setChecked(True)
  90. # else:
  91. # self.btn2.setChecked(True)
  92. #
  93. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  94. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  95. #
  96. # def btn_state(self, btn):
  97. # if btn.text() == self.lbl1:
  98. # if btn.isChecked() is True:
  99. # self.show_widgets(self.show_list)
  100. # self.hide_widgets(self.hide_list)
  101. # else:
  102. # self.show_widgets(self.hide_list)
  103. # self.hide_widgets(self.show_list)
  104. #
  105. # def hide_widgets(self, lst):
  106. # for wgt in lst:
  107. # wgt.hide()
  108. #
  109. # def show_widgets(self, lst):
  110. # for wgt in lst:
  111. # wgt.show()
  112. class LengthEntry(QtWidgets.QLineEdit):
  113. def __init__(self, output_units='IN', parent=None):
  114. super(LengthEntry, self).__init__(parent)
  115. self.output_units = output_units
  116. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  117. # Unit conversion table OUTPUT-INPUT
  118. self.scales = {
  119. 'IN': {'IN': 1.0,
  120. 'MM': 1/25.4},
  121. 'MM': {'IN': 25.4,
  122. 'MM': 1.0}
  123. }
  124. self.readyToEdit = True
  125. def mousePressEvent(self, e, Parent=None):
  126. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  127. if self.readyToEdit:
  128. self.selectAll()
  129. self.readyToEdit = False
  130. def focusOutEvent(self, e):
  131. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  132. self.deselect()
  133. self.readyToEdit = True
  134. def returnPressed(self, *args, **kwargs):
  135. val = self.get_value()
  136. if val is not None:
  137. self.set_text(str(val))
  138. else:
  139. log.warning("Could not interpret entry: %s" % self.get_text())
  140. def get_value(self):
  141. raw = str(self.text()).strip(' ')
  142. # match = self.format_re.search(raw)
  143. try:
  144. units = raw[-2:]
  145. units = self.scales[self.output_units][units.upper()]
  146. value = raw[:-2]
  147. return float(eval(value))*units
  148. except IndexError:
  149. value = raw
  150. return float(eval(value))
  151. except KeyError:
  152. value = raw
  153. return float(eval(value))
  154. except:
  155. log.warning("Could not parse value in entry: %s" % str(raw))
  156. return None
  157. def set_value(self, val):
  158. self.setText(str('%.4f' % val))
  159. def sizeHint(self):
  160. default_hint_size = super(LengthEntry, self).sizeHint()
  161. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  162. class FloatEntry(QtWidgets.QLineEdit):
  163. def __init__(self, parent=None):
  164. super(FloatEntry, self).__init__(parent)
  165. self.readyToEdit = True
  166. def mousePressEvent(self, e, Parent=None):
  167. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  168. if self.readyToEdit:
  169. self.selectAll()
  170. self.readyToEdit = False
  171. def focusOutEvent(self, e):
  172. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  173. self.deselect()
  174. self.readyToEdit = True
  175. def returnPressed(self, *args, **kwargs):
  176. val = self.get_value()
  177. if val is not None:
  178. self.set_text(str(val))
  179. else:
  180. log.warning("Could not interpret entry: %s" % self.text())
  181. def get_value(self):
  182. raw = str(self.text()).strip(' ')
  183. evaled = 0.0
  184. try:
  185. evaled = eval(raw)
  186. except:
  187. if evaled is not None:
  188. log.error("Could not evaluate: %s" % str(raw))
  189. return None
  190. return float(evaled)
  191. def set_value(self, val):
  192. if val is not None:
  193. self.setText("%.6f" % val)
  194. else:
  195. self.setText("")
  196. def sizeHint(self):
  197. default_hint_size = super(FloatEntry, self).sizeHint()
  198. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  199. class FloatEntry2(QtWidgets.QLineEdit):
  200. def __init__(self, parent=None):
  201. super(FloatEntry2, self).__init__(parent)
  202. self.readyToEdit = True
  203. def mousePressEvent(self, e, Parent=None):
  204. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  205. if self.readyToEdit:
  206. self.selectAll()
  207. self.readyToEdit = False
  208. def focusOutEvent(self, e):
  209. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  210. self.deselect()
  211. self.readyToEdit = True
  212. def get_value(self):
  213. raw = str(self.text()).strip(' ')
  214. evaled = 0.0
  215. try:
  216. evaled = eval(raw)
  217. except:
  218. if evaled is not None:
  219. log.error("Could not evaluate: %s" % str(raw))
  220. return None
  221. return float(evaled)
  222. def set_value(self, val):
  223. self.setText("%.6f" % val)
  224. def sizeHint(self):
  225. default_hint_size = super(FloatEntry2, self).sizeHint()
  226. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  227. class IntEntry(QtWidgets.QLineEdit):
  228. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  229. super(IntEntry, self).__init__(parent)
  230. self.allow_empty = allow_empty
  231. self.empty_val = empty_val
  232. self.readyToEdit = True
  233. def mousePressEvent(self, e, Parent=None):
  234. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  235. if self.readyToEdit:
  236. self.selectAll()
  237. self.readyToEdit = False
  238. def focusOutEvent(self, e):
  239. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  240. self.deselect()
  241. self.readyToEdit = True
  242. def get_value(self):
  243. if self.allow_empty:
  244. if str(self.text()) == "":
  245. return self.empty_val
  246. # make the text() first a float and then int because if text is a float type,
  247. # the int() can't convert directly a "text float" into a int type.
  248. ret_val = float(self.text())
  249. ret_val = int(ret_val)
  250. return ret_val
  251. def set_value(self, val):
  252. if val == self.empty_val and self.allow_empty:
  253. self.setText("")
  254. return
  255. self.setText(str(val))
  256. def sizeHint(self):
  257. default_hint_size = super(IntEntry, self).sizeHint()
  258. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  259. class FCEntry(QtWidgets.QLineEdit):
  260. def __init__(self, parent=None):
  261. super(FCEntry, self).__init__(parent)
  262. self.readyToEdit = True
  263. def mousePressEvent(self, e, Parent=None):
  264. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  265. if self.readyToEdit:
  266. self.selectAll()
  267. self.readyToEdit = False
  268. def focusOutEvent(self, e):
  269. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  270. self.deselect()
  271. self.readyToEdit = True
  272. def get_value(self):
  273. return str(self.text())
  274. def set_value(self, val):
  275. self.setText(str(val))
  276. def sizeHint(self):
  277. default_hint_size = super(FCEntry, self).sizeHint()
  278. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  279. class FCEntry2(FCEntry):
  280. def __init__(self, parent=None):
  281. super(FCEntry2, self).__init__(parent)
  282. self.readyToEdit = True
  283. def set_value(self, val):
  284. self.setText('%.5f' % float(val))
  285. class EvalEntry(QtWidgets.QLineEdit):
  286. def __init__(self, parent=None):
  287. super(EvalEntry, self).__init__(parent)
  288. self.readyToEdit = True
  289. def mousePressEvent(self, e, Parent=None):
  290. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  291. if self.readyToEdit:
  292. self.selectAll()
  293. self.readyToEdit = False
  294. def focusOutEvent(self, e):
  295. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  296. self.deselect()
  297. self.readyToEdit = True
  298. def returnPressed(self, *args, **kwargs):
  299. val = self.get_value()
  300. if val is not None:
  301. self.setText(str(val))
  302. else:
  303. log.warning("Could not interpret entry: %s" % self.get_text())
  304. def get_value(self):
  305. raw = str(self.text()).strip(' ')
  306. evaled = 0.0
  307. try:
  308. evaled = eval(raw)
  309. except:
  310. if evaled is not None:
  311. log.error("Could not evaluate: %s" % str(raw))
  312. return None
  313. return evaled
  314. def set_value(self, val):
  315. self.setText(str(val))
  316. def sizeHint(self):
  317. default_hint_size = super(EvalEntry, self).sizeHint()
  318. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  319. class EvalEntry2(QtWidgets.QLineEdit):
  320. def __init__(self, parent=None):
  321. super(EvalEntry2, self).__init__(parent)
  322. self.readyToEdit = True
  323. def mousePressEvent(self, e, Parent=None):
  324. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  325. if self.readyToEdit:
  326. self.selectAll()
  327. self.readyToEdit = False
  328. def focusOutEvent(self, e):
  329. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  330. self.deselect()
  331. self.readyToEdit = True
  332. def get_value(self):
  333. raw = str(self.text()).strip(' ')
  334. evaled = 0.0
  335. try:
  336. evaled = eval(raw)
  337. except:
  338. if evaled is not None:
  339. log.error("Could not evaluate: %s" % str(raw))
  340. return None
  341. return evaled
  342. def set_value(self, val):
  343. self.setText(str(val))
  344. def sizeHint(self):
  345. default_hint_size = super(EvalEntry2, self).sizeHint()
  346. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  347. class FCCheckBox(QtWidgets.QCheckBox):
  348. def __init__(self, label='', parent=None):
  349. super(FCCheckBox, self).__init__(str(label), parent)
  350. def get_value(self):
  351. return self.isChecked()
  352. def set_value(self, val):
  353. self.setChecked(val)
  354. def toggle(self):
  355. self.set_value(not self.get_value())
  356. class FCTextArea(QtWidgets.QPlainTextEdit):
  357. def __init__(self, parent=None):
  358. super(FCTextArea, self).__init__(parent)
  359. def set_value(self, val):
  360. self.setPlainText(val)
  361. def get_value(self):
  362. return str(self.toPlainText())
  363. def sizeHint(self):
  364. default_hint_size = super(FCTextArea, self).sizeHint()
  365. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  366. class FCTextAreaRich(QtWidgets.QTextEdit):
  367. def __init__(self, parent=None):
  368. super(FCTextAreaRich, self).__init__(parent)
  369. def set_value(self, val):
  370. self.setText(val)
  371. def get_value(self):
  372. return str(self.toPlainText())
  373. def sizeHint(self):
  374. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  375. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  376. class FCComboBox(QtWidgets.QComboBox):
  377. def __init__(self, parent=None):
  378. super(FCComboBox, self).__init__(parent)
  379. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  380. def wheelEvent(self, *args, **kwargs):
  381. pass
  382. def get_value(self):
  383. return str(self.currentText())
  384. def set_value(self, val):
  385. self.setCurrentIndex(self.findText(str(val)))
  386. class FCInputDialog(QtWidgets.QInputDialog):
  387. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None):
  388. super(FCInputDialog, self).__init__(parent)
  389. self.allow_empty = ok
  390. self.empty_val = val
  391. if title is None:
  392. self.title = 'title'
  393. else:
  394. self.title = title
  395. if text is None:
  396. self.text = 'text'
  397. else:
  398. self.text = text
  399. if min is None:
  400. self.min = 0
  401. else:
  402. self.min = min
  403. if max is None:
  404. self.max = 0
  405. else:
  406. self.max = max
  407. if decimals is None:
  408. self.decimals = 6
  409. else:
  410. self.decimals = decimals
  411. def get_value(self):
  412. self.val,self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  413. max=self.max, decimals=self.decimals)
  414. return [self.val, self.ok]
  415. # "Transform", "Enter the Angle value:"
  416. def set_value(self, val):
  417. pass
  418. class FCButton(QtWidgets.QPushButton):
  419. def __init__(self, parent=None):
  420. super(FCButton, self).__init__(parent)
  421. def get_value(self):
  422. return self.isChecked()
  423. def set_value(self, val):
  424. self.setText(str(val))
  425. class FCTab(QtWidgets.QTabWidget):
  426. def __init__(self, parent=None):
  427. super(FCTab, self).__init__(parent)
  428. self.setTabsClosable(True)
  429. self.tabCloseRequested.connect(self.closeTab)
  430. def deleteTab(self, currentIndex):
  431. widget = self.widget(currentIndex)
  432. if widget is not None:
  433. widget.deleteLater()
  434. self.removeTab(currentIndex)
  435. def closeTab(self, currentIndex):
  436. self.removeTab(currentIndex)
  437. def protectTab(self, currentIndex):
  438. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  439. class FCDetachableTab(QtWidgets.QTabWidget):
  440. # From here: https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  441. def __init__(self, protect=None, protect_by_name=None, parent=None):
  442. super().__init__()
  443. self.tabBar = self.FCTabBar(self)
  444. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  445. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  446. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  447. self.setTabBar(self.tabBar)
  448. # Used to keep a reference to detached tabs since their QMainWindow
  449. # does not have a parent
  450. self.detachedTabs = {}
  451. # a way to make sure that tabs can't be closed after they attach to the parent tab
  452. self.protect_tab = True if protect is not None and protect is True else False
  453. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  454. # Close all detached tabs if the application is closed explicitly
  455. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  456. # used by the property self.useOldIndex(param)
  457. self.use_old_index = None
  458. self.old_index = None
  459. self.setTabsClosable(True)
  460. self.tabCloseRequested.connect(self.closeTab)
  461. def useOldIndex(self, param):
  462. if param:
  463. self.use_old_index = True
  464. else:
  465. self.use_old_index = False
  466. def deleteTab(self, currentIndex):
  467. widget = self.widget(currentIndex)
  468. if widget is not None:
  469. widget.deleteLater()
  470. self.removeTab(currentIndex)
  471. def closeTab(self, currentIndex):
  472. self.removeTab(currentIndex)
  473. def protectTab(self, currentIndex):
  474. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  475. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  476. ##
  477. # The default movable functionality of QTabWidget must remain disabled
  478. # so as not to conflict with the added features
  479. def setMovable(self, movable):
  480. pass
  481. ##
  482. # Move a tab from one position (index) to another
  483. #
  484. # @param fromIndex the original index location of the tab
  485. # @param toIndex the new index location of the tab
  486. @pyqtSlot(int, int)
  487. def moveTab(self, fromIndex, toIndex):
  488. widget = self.widget(fromIndex)
  489. icon = self.tabIcon(fromIndex)
  490. text = self.tabText(fromIndex)
  491. self.removeTab(fromIndex)
  492. self.insertTab(toIndex, widget, icon, text)
  493. self.setCurrentIndex(toIndex)
  494. ##
  495. # Detach the tab by removing it's contents and placing them in
  496. # a DetachedTab window
  497. #
  498. # @param index the index location of the tab to be detached
  499. # @param point the screen position for creating the new DetachedTab window
  500. @pyqtSlot(int, QtCore.QPoint)
  501. def detachTab(self, index, point):
  502. self.old_index = index
  503. # Get the tab content
  504. name = self.tabText(index)
  505. icon = self.tabIcon(index)
  506. if icon.isNull():
  507. icon = self.window().windowIcon()
  508. contentWidget = self.widget(index)
  509. try:
  510. contentWidgetRect = contentWidget.frameGeometry()
  511. except AttributeError:
  512. return
  513. # Create a new detached tab window
  514. detachedTab = self.FCDetachedTab(name, contentWidget)
  515. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  516. detachedTab.setWindowIcon(icon)
  517. detachedTab.setGeometry(contentWidgetRect)
  518. detachedTab.onCloseSignal.connect(self.attachTab)
  519. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  520. detachedTab.move(point)
  521. detachedTab.show()
  522. # Create a reference to maintain access to the detached tab
  523. self.detachedTabs[name] = detachedTab
  524. ##
  525. # Re-attach the tab by removing the content from the DetachedTab window,
  526. # closing it, and placing the content back into the DetachableTabWidget
  527. #
  528. # @param contentWidget the content widget from the DetachedTab window
  529. # @param name the name of the detached tab
  530. # @param icon the window icon for the detached tab
  531. # @param insertAt insert the re-attached tab at the given index
  532. def attachTab(self, contentWidget, name, icon, insertAt=None):
  533. # Make the content widget a child of this widget
  534. contentWidget.setParent(self)
  535. # Remove the reference
  536. del self.detachedTabs[name]
  537. # helps in restoring the tab to the same index that it was before was detached
  538. insert_index = self.old_index if self.use_old_index is True else insertAt
  539. # Create an image from the given icon (for comparison)
  540. if not icon.isNull():
  541. try:
  542. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  543. tabIconImage = tabIconPixmap.toImage()
  544. except IndexError:
  545. tabIconImage = None
  546. else:
  547. tabIconImage = None
  548. # Create an image of the main window icon (for comparison)
  549. if not icon.isNull():
  550. try:
  551. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  552. windowIconImage = windowIconPixmap.toImage()
  553. except IndexError:
  554. windowIconImage = None
  555. else:
  556. windowIconImage = None
  557. # Determine if the given image and the main window icon are the same.
  558. # If they are, then do not add the icon to the tab
  559. if tabIconImage == windowIconImage:
  560. if insert_index is None:
  561. index = self.addTab(contentWidget, name)
  562. else:
  563. index = self.insertTab(insert_index, contentWidget, name)
  564. else:
  565. if insert_index is None:
  566. index = self.addTab(contentWidget, icon, name)
  567. else:
  568. index = self.insertTab(insert_index, contentWidget, icon, name)
  569. # on reattaching the tab if protect is true then the closure button is not added
  570. if self.protect_tab is True:
  571. self.protectTab(index)
  572. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  573. if self.protect_by_name is not None:
  574. for tab_name in self.protect_by_name:
  575. for index in range(self.count()):
  576. if str(tab_name) == str(self.tabText(index)):
  577. self.protectTab(index)
  578. # Make this tab the current tab
  579. if index > -1:
  580. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  581. ##
  582. # Remove the tab with the given name, even if it is detached
  583. #
  584. # @param name the name of the tab to be removed
  585. def removeTabByName(self, name):
  586. # Remove the tab if it is attached
  587. attached = False
  588. for index in range(self.count()):
  589. if str(name) == str(self.tabText(index)):
  590. self.removeTab(index)
  591. attached = True
  592. break
  593. # If the tab is not attached, close it's window and
  594. # remove the reference to it
  595. if not attached:
  596. for key in self.detachedTabs:
  597. if str(name) == str(key):
  598. self.detachedTabs[key].onCloseSignal.disconnect()
  599. self.detachedTabs[key].close()
  600. del self.detachedTabs[key]
  601. break
  602. ##
  603. # Handle dropping of a detached tab inside the DetachableTabWidget
  604. #
  605. # @param name the name of the detached tab
  606. # @param index the index of an existing tab (if the tab bar
  607. # determined that the drop occurred on an
  608. # existing tab)
  609. # @param dropPos the mouse cursor position when the drop occurred
  610. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  611. def detachedTabDrop(self, name, index, dropPos):
  612. # If the drop occurred on an existing tab, insert the detached
  613. # tab at the existing tab's location
  614. if index > -1:
  615. # Create references to the detached tab's content and icon
  616. contentWidget = self.detachedTabs[name].contentWidget
  617. icon = self.detachedTabs[name].windowIcon()
  618. # Disconnect the detached tab's onCloseSignal so that it
  619. # does not try to re-attach automatically
  620. self.detachedTabs[name].onCloseSignal.disconnect()
  621. # Close the detached
  622. self.detachedTabs[name].close()
  623. # Re-attach the tab at the given index
  624. self.attachTab(contentWidget, name, icon, index)
  625. # If the drop did not occur on an existing tab, determine if the drop
  626. # occurred in the tab bar area (the area to the side of the QTabBar)
  627. else:
  628. # Find the drop position relative to the DetachableTabWidget
  629. tabDropPos = self.mapFromGlobal(dropPos)
  630. # If the drop position is inside the DetachableTabWidget...
  631. if self.rect().contains(tabDropPos):
  632. # If the drop position is inside the tab bar area (the
  633. # area to the side of the QTabBar) or there are not tabs
  634. # currently attached...
  635. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  636. # Close the detached tab and allow it to re-attach
  637. # automatically
  638. self.detachedTabs[name].close()
  639. ##
  640. # Close all tabs that are currently detached.
  641. def closeDetachedTabs(self):
  642. listOfDetachedTabs = []
  643. for key in self.detachedTabs:
  644. listOfDetachedTabs.append(self.detachedTabs[key])
  645. for detachedTab in listOfDetachedTabs:
  646. detachedTab.close()
  647. ##
  648. # When a tab is detached, the contents are placed into this QMainWindow. The tab
  649. # can be re-attached by closing the dialog or by dragging the window into the tab bar
  650. class FCDetachedTab(QtWidgets.QMainWindow):
  651. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  652. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  653. def __init__(self, name, contentWidget):
  654. QtWidgets.QMainWindow.__init__(self, None)
  655. self.setObjectName(name)
  656. self.setWindowTitle(name)
  657. self.contentWidget = contentWidget
  658. self.setCentralWidget(self.contentWidget)
  659. self.contentWidget.show()
  660. self.windowDropFilter = self.WindowDropFilter()
  661. self.installEventFilter(self.windowDropFilter)
  662. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  663. ##
  664. # Handle a window drop event
  665. #
  666. # @param dropPos the mouse cursor position of the drop
  667. @QtCore.pyqtSlot(QtCore.QPoint)
  668. def windowDropSlot(self, dropPos):
  669. self.onDropSignal.emit(self.objectName(), dropPos)
  670. ##
  671. # If the window is closed, emit the onCloseSignal and give the
  672. # content widget back to the DetachableTabWidget
  673. #
  674. # @param event a close event
  675. def closeEvent(self, event):
  676. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  677. ##
  678. # An event filter class to detect a QMainWindow drop event
  679. class WindowDropFilter(QtCore.QObject):
  680. onDropSignal = pyqtSignal(QtCore.QPoint)
  681. def __init__(self):
  682. QtCore.QObject.__init__(self)
  683. self.lastEvent = None
  684. ##
  685. # Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  686. # event that immediately follows a Move event
  687. #
  688. # @param obj the object that generated the event
  689. # @param event the current event
  690. def eventFilter(self, obj, event):
  691. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  692. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  693. # Determine the position of the mouse cursor and emit it with the
  694. # onDropSignal
  695. mouseCursor = QtGui.QCursor()
  696. dropPos = mouseCursor.pos()
  697. self.onDropSignal.emit(dropPos)
  698. self.lastEvent = event.type()
  699. return True
  700. else:
  701. self.lastEvent = event.type()
  702. return False
  703. class FCTabBar(QtWidgets.QTabBar):
  704. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  705. onMoveTabSignal = pyqtSignal(int, int)
  706. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  707. def __init__(self, parent=None):
  708. QtWidgets.QTabBar.__init__(self, parent)
  709. self.setAcceptDrops(True)
  710. self.setElideMode(QtCore.Qt.ElideRight)
  711. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  712. self.dragStartPos = QtCore.QPoint()
  713. self.dragDropedPos = QtCore.QPoint()
  714. self.mouseCursor = QtGui.QCursor()
  715. self.dragInitiated = False
  716. # Send the onDetachTabSignal when a tab is double clicked
  717. #
  718. # @param event a mouse double click event
  719. def mouseDoubleClickEvent(self, event):
  720. event.accept()
  721. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  722. # Set the starting position for a drag event when the mouse button is pressed
  723. #
  724. # @param event a mouse press event
  725. def mousePressEvent(self, event):
  726. if event.button() == QtCore.Qt.LeftButton:
  727. self.dragStartPos = event.pos()
  728. self.dragDropedPos.setX(0)
  729. self.dragDropedPos.setY(0)
  730. self.dragInitiated = False
  731. QtWidgets.QTabBar.mousePressEvent(self, event)
  732. # Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  733. # drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  734. # bar, emit an onDetachTabSignal.
  735. #
  736. # @param event a mouse move event
  737. def mouseMoveEvent(self, event):
  738. # Determine if the current movement is detected as a drag
  739. if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  740. self.dragInitiated = True
  741. # If the current movement is a drag initiated by the left button
  742. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  743. # Stop the move event
  744. finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
  745. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  746. # Convert the move event into a drag
  747. drag = QtGui.QDrag(self)
  748. mimeData = QtCore.QMimeData()
  749. # mimeData.setData('action', 'application/tab-detach')
  750. drag.setMimeData(mimeData)
  751. # screen = QScreen(self.parentWidget().currentWidget().winId())
  752. # Create the appearance of dragging the tab content
  753. try:
  754. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  755. except Exception as e:
  756. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  757. return
  758. targetPixmap = QtGui.QPixmap(pixmap.size())
  759. targetPixmap.fill(QtCore.Qt.transparent)
  760. painter = QtGui.QPainter(targetPixmap)
  761. painter.setOpacity(0.85)
  762. painter.drawPixmap(0, 0, pixmap)
  763. painter.end()
  764. drag.setPixmap(targetPixmap)
  765. # Initiate the drag
  766. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  767. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  768. # must be set manually
  769. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  770. dropAction = QtCore.Qt.MoveAction
  771. # If the drag completed outside of the tab bar, detach the tab and move
  772. # the content to the current cursor position
  773. if dropAction == QtCore.Qt.IgnoreAction:
  774. event.accept()
  775. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  776. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  777. elif dropAction == QtCore.Qt.MoveAction:
  778. if not self.dragDropedPos.isNull():
  779. event.accept()
  780. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  781. else:
  782. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  783. # Determine if the drag has entered a tab position from another tab position
  784. #
  785. # @param event a drag enter event
  786. def dragEnterEvent(self, event):
  787. mimeData = event.mimeData()
  788. # formats = mcd imeData.formats()
  789. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  790. # event.acceptProposedAction()
  791. QtWidgets.QTabBar.dragMoveEvent(self, event)
  792. # Get the position of the end of the drag
  793. #
  794. # @param event a drop event
  795. def dropEvent(self, event):
  796. self.dragDropedPos = event.pos()
  797. QtWidgets.QTabBar.dropEvent(self, event)
  798. # Determine if the detached tab drop event occurred on an existing tab,
  799. # then send the event to the DetachableTabWidget
  800. def detachedTabDrop(self, name, dropPos):
  801. tabDropPos = self.mapFromGlobal(dropPos)
  802. index = self.tabAt(tabDropPos)
  803. self.detachedTabDropSignal.emit(name, index, dropPos)
  804. class VerticalScrollArea(QtWidgets.QScrollArea):
  805. """
  806. This widget extends QtGui.QScrollArea to make a vertical-only
  807. scroll area that also expands horizontally to accomodate
  808. its contents.
  809. """
  810. def __init__(self, parent=None):
  811. QtWidgets.QScrollArea.__init__(self, parent=parent)
  812. self.setWidgetResizable(True)
  813. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  814. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  815. def eventFilter(self, source, event):
  816. """
  817. The event filter gets automatically installed when setWidget()
  818. is called.
  819. :param source:
  820. :param event:
  821. :return:
  822. """
  823. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  824. # log.debug("VerticalScrollArea: Widget resized:")
  825. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  826. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  827. self.setMinimumWidth(self.widget().sizeHint().width() +
  828. self.verticalScrollBar().sizeHint().width())
  829. # if self.verticalScrollBar().isVisible():
  830. # log.debug(" Scroll bar visible")
  831. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  832. # self.verticalScrollBar().width())
  833. # else:
  834. # log.debug(" Scroll bar hidden")
  835. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  836. return QtWidgets.QWidget.eventFilter(self, source, event)
  837. class OptionalInputSection:
  838. def __init__(self, cb, optinputs, logic=True):
  839. """
  840. Associates the a checkbox with a set of inputs.
  841. :param cb: Checkbox that enables the optional inputs.
  842. :param optinputs: List of widgets that are optional.
  843. :param logic: When True the logic is normal, when False the logic is in reverse
  844. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  845. for logic=False, when the checkbox is checked the widgets are Disabled
  846. :return:
  847. """
  848. assert isinstance(cb, FCCheckBox), \
  849. "Expected an FCCheckBox, got %s" % type(cb)
  850. self.cb = cb
  851. self.optinputs = optinputs
  852. self.logic = logic
  853. self.on_cb_change()
  854. self.cb.stateChanged.connect(self.on_cb_change)
  855. def on_cb_change(self):
  856. if self.cb.checkState():
  857. for widget in self.optinputs:
  858. if self.logic is True:
  859. widget.setEnabled(True)
  860. else:
  861. widget.setEnabled(False)
  862. else:
  863. for widget in self.optinputs:
  864. if self.logic is True:
  865. widget.setEnabled(False)
  866. else:
  867. widget.setEnabled(True)
  868. class FCTable(QtWidgets.QTableWidget):
  869. def __init__(self, parent=None):
  870. super(FCTable, self).__init__(parent)
  871. def sizeHint(self):
  872. default_hint_size = super(FCTable, self).sizeHint()
  873. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  874. def getHeight(self):
  875. height = self.horizontalHeader().height()
  876. for i in range(self.rowCount()):
  877. height += self.rowHeight(i)
  878. return height
  879. def getWidth(self):
  880. width = self.verticalHeader().width()
  881. for i in range(self.columnCount()):
  882. width += self.columnWidth(i)
  883. return width
  884. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  885. def setColortoRow(self, rowIndex, color):
  886. for j in range(self.columnCount()):
  887. self.item(rowIndex, j).setBackground(color)
  888. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  889. def mousePressEvent(self, event):
  890. if self.itemAt(event.pos()) is None:
  891. self.clearSelection()
  892. else:
  893. QtWidgets.QTableWidget.mousePressEvent(self, event)
  894. def setupContextMenu(self):
  895. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  896. def addContextMenu(self, entry, call_function, icon=None):
  897. action_name = str(entry)
  898. action = QtWidgets.QAction(self)
  899. action.setText(action_name)
  900. if icon:
  901. assert isinstance(icon, QtGui.QIcon), \
  902. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  903. action.setIcon(icon)
  904. self.addAction(action)
  905. action.triggered.connect(call_function)
  906. class FCSpinner(QtWidgets.QSpinBox):
  907. def __init__(self, parent=None):
  908. super(FCSpinner, self).__init__(parent)
  909. def get_value(self):
  910. return str(self.value())
  911. def set_value(self, val):
  912. try:
  913. k = int(val)
  914. except Exception as e:
  915. log.debug(str(e))
  916. return
  917. self.setValue(k)
  918. # def sizeHint(self):
  919. # default_hint_size = super(FCSpinner, self).sizeHint()
  920. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  921. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  922. def __init__(self, parent=None):
  923. super(FCDoubleSpinner, self).__init__(parent)
  924. self.readyToEdit = True
  925. def mousePressEvent(self, e, parent=None):
  926. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  927. if self.readyToEdit:
  928. self.lineEdit().selectAll()
  929. self.readyToEdit = False
  930. def focusOutEvent(self, e):
  931. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  932. self.lineEdit().deselect()
  933. self.readyToEdit = True
  934. def get_value(self):
  935. return str(self.value())
  936. def set_value(self, val):
  937. try:
  938. k = int(val)
  939. except Exception as e:
  940. log.debug(str(e))
  941. return
  942. self.setValue(k)
  943. def set_precision(self, val):
  944. self.setDecimals(val)
  945. def set_range(self, min_val, max_val):
  946. self.setRange(self, min_val, max_val)
  947. class Dialog_box(QtWidgets.QWidget):
  948. def __init__(self, title=None, label=None):
  949. """
  950. :param title: string with the window title
  951. :param label: string with the message inside the dialog box
  952. """
  953. super(Dialog_box, self).__init__()
  954. self.location = (0, 0)
  955. self.ok = False
  956. dialog_box = QtWidgets.QInputDialog()
  957. dialog_box.setFixedWidth(270)
  958. self.location, self.ok = dialog_box.getText(self, title, label)
  959. class _BrowserTextEdit(QTextEdit):
  960. def __init__(self, version):
  961. QTextEdit.__init__(self)
  962. self.menu = None
  963. self.version = version
  964. def contextMenuEvent(self, event):
  965. self.menu = self.createStandardContextMenu(event.pos())
  966. clear_action = QAction("Clear", self)
  967. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  968. self.menu.addAction(clear_action)
  969. clear_action.triggered.connect(self.clear)
  970. self.menu.exec_(event.globalPos())
  971. def clear(self):
  972. QTextEdit.clear(self)
  973. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  974. text = html.escape(text)
  975. text = text.replace('\n', '<br/>')
  976. self.moveCursor(QTextCursor.End)
  977. self.insertHtml(text)
  978. class _ExpandableTextEdit(QTextEdit):
  979. """
  980. Class implements edit line, which expands themselves automatically
  981. """
  982. historyNext = pyqtSignal()
  983. historyPrev = pyqtSignal()
  984. def __init__(self, termwidget, *args):
  985. QTextEdit.__init__(self, *args)
  986. self.setStyleSheet("font: 9pt \"Courier\";")
  987. self._fittedHeight = 1
  988. self.textChanged.connect(self._fit_to_document)
  989. self._fit_to_document()
  990. self._termWidget = termwidget
  991. self.completer = MyCompleter()
  992. self.model = QtCore.QStringListModel()
  993. self.completer.setModel(self.model)
  994. self.set_model_data(keyword_list=[])
  995. self.completer.insertText.connect(self.insertCompletion)
  996. def set_model_data(self, keyword_list):
  997. self.model.setStringList(keyword_list)
  998. def insertCompletion(self, completion):
  999. tc = self.textCursor()
  1000. extra = (len(completion) - len(self.completer.completionPrefix()))
  1001. tc.movePosition(QTextCursor.Left)
  1002. tc.movePosition(QTextCursor.EndOfWord)
  1003. tc.insertText(completion[-extra:])
  1004. self.setTextCursor(tc)
  1005. self.completer.popup().hide()
  1006. def focusInEvent(self, event):
  1007. if self.completer:
  1008. self.completer.setWidget(self)
  1009. QTextEdit.focusInEvent(self, event)
  1010. def keyPressEvent(self, event):
  1011. """
  1012. Catch keyboard events. Process Enter, Up, Down
  1013. """
  1014. if event.matches(QKeySequence.InsertParagraphSeparator):
  1015. text = self.toPlainText()
  1016. if self._termWidget.is_command_complete(text):
  1017. self._termWidget.exec_current_command()
  1018. return
  1019. elif event.matches(QKeySequence.MoveToNextLine):
  1020. text = self.toPlainText()
  1021. cursor_pos = self.textCursor().position()
  1022. textBeforeEnd = text[cursor_pos:]
  1023. if len(textBeforeEnd.split('\n')) <= 1:
  1024. self.historyNext.emit()
  1025. return
  1026. elif event.matches(QKeySequence.MoveToPreviousLine):
  1027. text = self.toPlainText()
  1028. cursor_pos = self.textCursor().position()
  1029. text_before_start = text[:cursor_pos]
  1030. # lineCount = len(textBeforeStart.splitlines())
  1031. line_count = len(text_before_start.split('\n'))
  1032. if len(text_before_start) > 0 and \
  1033. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1034. line_count += 1
  1035. if line_count <= 1:
  1036. self.historyPrev.emit()
  1037. return
  1038. elif event.matches(QKeySequence.MoveToNextPage) or \
  1039. event.matches(QKeySequence.MoveToPreviousPage):
  1040. return self._termWidget.browser().keyPressEvent(event)
  1041. tc = self.textCursor()
  1042. if event.key() == Qt.Key_Tab and self.completer.popup().isVisible():
  1043. self.completer.insertText.emit(self.completer.getSelected())
  1044. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1045. return
  1046. QTextEdit.keyPressEvent(self, event)
  1047. tc.select(QTextCursor.WordUnderCursor)
  1048. cr = self.cursorRect()
  1049. if len(tc.selectedText()) > 0:
  1050. self.completer.setCompletionPrefix(tc.selectedText())
  1051. popup = self.completer.popup()
  1052. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1053. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1054. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1055. self.completer.complete(cr)
  1056. else:
  1057. self.completer.popup().hide()
  1058. def sizeHint(self):
  1059. """
  1060. QWidget sizeHint impelemtation
  1061. """
  1062. hint = QTextEdit.sizeHint(self)
  1063. hint.setHeight(self._fittedHeight)
  1064. return hint
  1065. def _fit_to_document(self):
  1066. """
  1067. Update widget height to fit all text
  1068. """
  1069. documentsize = self.document().size().toSize()
  1070. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1071. self.setMaximumHeight(self._fittedHeight)
  1072. self.updateGeometry()
  1073. def insertFromMimeData(self, mime_data):
  1074. # Paste only plain text.
  1075. self.insertPlainText(mime_data.text())
  1076. class MyCompleter(QCompleter):
  1077. insertText = pyqtSignal(str)
  1078. def __init__(self, parent=None):
  1079. QCompleter.__init__(self)
  1080. self.setCompletionMode(QCompleter.PopupCompletion)
  1081. self.highlighted.connect(self.setHighlighted)
  1082. def setHighlighted(self, text):
  1083. self.lastSelected = text
  1084. def getSelected(self):
  1085. return self.lastSelected