GUIElements.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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('%.4f' % 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. self.val = 0.0
  392. self.ok = ''
  393. if title is None:
  394. self.title = 'title'
  395. else:
  396. self.title = title
  397. if text is None:
  398. self.text = 'text'
  399. else:
  400. self.text = text
  401. if min is None:
  402. self.min = 0
  403. else:
  404. self.min = min
  405. if max is None:
  406. self.max = 0
  407. else:
  408. self.max = max
  409. if decimals is None:
  410. self.decimals = 6
  411. else:
  412. self.decimals = decimals
  413. def get_value(self):
  414. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  415. max=self.max, decimals=self.decimals)
  416. return [self.val, self.ok]
  417. # "Transform", "Enter the Angle value:"
  418. def set_value(self, val):
  419. pass
  420. class FCButton(QtWidgets.QPushButton):
  421. def __init__(self, parent=None):
  422. super(FCButton, self).__init__(parent)
  423. def get_value(self):
  424. return self.isChecked()
  425. def set_value(self, val):
  426. self.setText(str(val))
  427. class FCTab(QtWidgets.QTabWidget):
  428. def __init__(self, parent=None):
  429. super(FCTab, self).__init__(parent)
  430. self.setTabsClosable(True)
  431. self.tabCloseRequested.connect(self.closeTab)
  432. def deleteTab(self, currentIndex):
  433. widget = self.widget(currentIndex)
  434. if widget is not None:
  435. widget.deleteLater()
  436. self.removeTab(currentIndex)
  437. def closeTab(self, currentIndex):
  438. self.removeTab(currentIndex)
  439. def protectTab(self, currentIndex):
  440. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  441. class FCDetachableTab(QtWidgets.QTabWidget):
  442. # From here: https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  443. def __init__(self, protect=None, protect_by_name=None, parent=None):
  444. super().__init__()
  445. self.tabBar = self.FCTabBar(self)
  446. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  447. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  448. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  449. self.setTabBar(self.tabBar)
  450. # Used to keep a reference to detached tabs since their QMainWindow
  451. # does not have a parent
  452. self.detachedTabs = {}
  453. # a way to make sure that tabs can't be closed after they attach to the parent tab
  454. self.protect_tab = True if protect is not None and protect is True else False
  455. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  456. # Close all detached tabs if the application is closed explicitly
  457. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  458. # used by the property self.useOldIndex(param)
  459. self.use_old_index = None
  460. self.old_index = None
  461. self.setTabsClosable(True)
  462. self.tabCloseRequested.connect(self.closeTab)
  463. def useOldIndex(self, param):
  464. if param:
  465. self.use_old_index = True
  466. else:
  467. self.use_old_index = False
  468. def deleteTab(self, currentIndex):
  469. widget = self.widget(currentIndex)
  470. if widget is not None:
  471. widget.deleteLater()
  472. self.removeTab(currentIndex)
  473. def closeTab(self, currentIndex):
  474. self.removeTab(currentIndex)
  475. def protectTab(self, currentIndex):
  476. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  477. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  478. ##
  479. # The default movable functionality of QTabWidget must remain disabled
  480. # so as not to conflict with the added features
  481. def setMovable(self, movable):
  482. pass
  483. ##
  484. # Move a tab from one position (index) to another
  485. #
  486. # @param fromIndex the original index location of the tab
  487. # @param toIndex the new index location of the tab
  488. @pyqtSlot(int, int)
  489. def moveTab(self, fromIndex, toIndex):
  490. widget = self.widget(fromIndex)
  491. icon = self.tabIcon(fromIndex)
  492. text = self.tabText(fromIndex)
  493. self.removeTab(fromIndex)
  494. self.insertTab(toIndex, widget, icon, text)
  495. self.setCurrentIndex(toIndex)
  496. ##
  497. # Detach the tab by removing it's contents and placing them in
  498. # a DetachedTab window
  499. #
  500. # @param index the index location of the tab to be detached
  501. # @param point the screen position for creating the new DetachedTab window
  502. @pyqtSlot(int, QtCore.QPoint)
  503. def detachTab(self, index, point):
  504. self.old_index = index
  505. # Get the tab content
  506. name = self.tabText(index)
  507. icon = self.tabIcon(index)
  508. if icon.isNull():
  509. icon = self.window().windowIcon()
  510. contentWidget = self.widget(index)
  511. try:
  512. contentWidgetRect = contentWidget.frameGeometry()
  513. except AttributeError:
  514. return
  515. # Create a new detached tab window
  516. detachedTab = self.FCDetachedTab(name, contentWidget)
  517. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  518. detachedTab.setWindowIcon(icon)
  519. detachedTab.setGeometry(contentWidgetRect)
  520. detachedTab.onCloseSignal.connect(self.attachTab)
  521. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  522. detachedTab.move(point)
  523. detachedTab.show()
  524. # Create a reference to maintain access to the detached tab
  525. self.detachedTabs[name] = detachedTab
  526. ##
  527. # Re-attach the tab by removing the content from the DetachedTab window,
  528. # closing it, and placing the content back into the DetachableTabWidget
  529. #
  530. # @param contentWidget the content widget from the DetachedTab window
  531. # @param name the name of the detached tab
  532. # @param icon the window icon for the detached tab
  533. # @param insertAt insert the re-attached tab at the given index
  534. def attachTab(self, contentWidget, name, icon, insertAt=None):
  535. # Make the content widget a child of this widget
  536. contentWidget.setParent(self)
  537. # Remove the reference
  538. del self.detachedTabs[name]
  539. # helps in restoring the tab to the same index that it was before was detached
  540. insert_index = self.old_index if self.use_old_index is True else insertAt
  541. # Create an image from the given icon (for comparison)
  542. if not icon.isNull():
  543. try:
  544. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  545. tabIconImage = tabIconPixmap.toImage()
  546. except IndexError:
  547. tabIconImage = None
  548. else:
  549. tabIconImage = None
  550. # Create an image of the main window icon (for comparison)
  551. if not icon.isNull():
  552. try:
  553. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  554. windowIconImage = windowIconPixmap.toImage()
  555. except IndexError:
  556. windowIconImage = None
  557. else:
  558. windowIconImage = None
  559. # Determine if the given image and the main window icon are the same.
  560. # If they are, then do not add the icon to the tab
  561. if tabIconImage == windowIconImage:
  562. if insert_index is None:
  563. index = self.addTab(contentWidget, name)
  564. else:
  565. index = self.insertTab(insert_index, contentWidget, name)
  566. else:
  567. if insert_index is None:
  568. index = self.addTab(contentWidget, icon, name)
  569. else:
  570. index = self.insertTab(insert_index, contentWidget, icon, name)
  571. # on reattaching the tab if protect is true then the closure button is not added
  572. if self.protect_tab is True:
  573. self.protectTab(index)
  574. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  575. if self.protect_by_name is not None:
  576. for tab_name in self.protect_by_name:
  577. for index in range(self.count()):
  578. if str(tab_name) == str(self.tabText(index)):
  579. self.protectTab(index)
  580. # Make this tab the current tab
  581. if index > -1:
  582. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  583. ##
  584. # Remove the tab with the given name, even if it is detached
  585. #
  586. # @param name the name of the tab to be removed
  587. def removeTabByName(self, name):
  588. # Remove the tab if it is attached
  589. attached = False
  590. for index in range(self.count()):
  591. if str(name) == str(self.tabText(index)):
  592. self.removeTab(index)
  593. attached = True
  594. break
  595. # If the tab is not attached, close it's window and
  596. # remove the reference to it
  597. if not attached:
  598. for key in self.detachedTabs:
  599. if str(name) == str(key):
  600. self.detachedTabs[key].onCloseSignal.disconnect()
  601. self.detachedTabs[key].close()
  602. del self.detachedTabs[key]
  603. break
  604. ##
  605. # Handle dropping of a detached tab inside the DetachableTabWidget
  606. #
  607. # @param name the name of the detached tab
  608. # @param index the index of an existing tab (if the tab bar
  609. # determined that the drop occurred on an
  610. # existing tab)
  611. # @param dropPos the mouse cursor position when the drop occurred
  612. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  613. def detachedTabDrop(self, name, index, dropPos):
  614. # If the drop occurred on an existing tab, insert the detached
  615. # tab at the existing tab's location
  616. if index > -1:
  617. # Create references to the detached tab's content and icon
  618. contentWidget = self.detachedTabs[name].contentWidget
  619. icon = self.detachedTabs[name].windowIcon()
  620. # Disconnect the detached tab's onCloseSignal so that it
  621. # does not try to re-attach automatically
  622. self.detachedTabs[name].onCloseSignal.disconnect()
  623. # Close the detached
  624. self.detachedTabs[name].close()
  625. # Re-attach the tab at the given index
  626. self.attachTab(contentWidget, name, icon, index)
  627. # If the drop did not occur on an existing tab, determine if the drop
  628. # occurred in the tab bar area (the area to the side of the QTabBar)
  629. else:
  630. # Find the drop position relative to the DetachableTabWidget
  631. tabDropPos = self.mapFromGlobal(dropPos)
  632. # If the drop position is inside the DetachableTabWidget...
  633. if self.rect().contains(tabDropPos):
  634. # If the drop position is inside the tab bar area (the
  635. # area to the side of the QTabBar) or there are not tabs
  636. # currently attached...
  637. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  638. # Close the detached tab and allow it to re-attach
  639. # automatically
  640. self.detachedTabs[name].close()
  641. ##
  642. # Close all tabs that are currently detached.
  643. def closeDetachedTabs(self):
  644. listOfDetachedTabs = []
  645. for key in self.detachedTabs:
  646. listOfDetachedTabs.append(self.detachedTabs[key])
  647. for detachedTab in listOfDetachedTabs:
  648. detachedTab.close()
  649. ##
  650. # When a tab is detached, the contents are placed into this QMainWindow. The tab
  651. # can be re-attached by closing the dialog or by dragging the window into the tab bar
  652. class FCDetachedTab(QtWidgets.QMainWindow):
  653. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  654. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  655. def __init__(self, name, contentWidget):
  656. QtWidgets.QMainWindow.__init__(self, None)
  657. self.setObjectName(name)
  658. self.setWindowTitle(name)
  659. self.contentWidget = contentWidget
  660. self.setCentralWidget(self.contentWidget)
  661. self.contentWidget.show()
  662. self.windowDropFilter = self.WindowDropFilter()
  663. self.installEventFilter(self.windowDropFilter)
  664. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  665. ##
  666. # Handle a window drop event
  667. #
  668. # @param dropPos the mouse cursor position of the drop
  669. @QtCore.pyqtSlot(QtCore.QPoint)
  670. def windowDropSlot(self, dropPos):
  671. self.onDropSignal.emit(self.objectName(), dropPos)
  672. ##
  673. # If the window is closed, emit the onCloseSignal and give the
  674. # content widget back to the DetachableTabWidget
  675. #
  676. # @param event a close event
  677. def closeEvent(self, event):
  678. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  679. ##
  680. # An event filter class to detect a QMainWindow drop event
  681. class WindowDropFilter(QtCore.QObject):
  682. onDropSignal = pyqtSignal(QtCore.QPoint)
  683. def __init__(self):
  684. QtCore.QObject.__init__(self)
  685. self.lastEvent = None
  686. ##
  687. # Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  688. # event that immediately follows a Move event
  689. #
  690. # @param obj the object that generated the event
  691. # @param event the current event
  692. def eventFilter(self, obj, event):
  693. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  694. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  695. # Determine the position of the mouse cursor and emit it with the
  696. # onDropSignal
  697. mouseCursor = QtGui.QCursor()
  698. dropPos = mouseCursor.pos()
  699. self.onDropSignal.emit(dropPos)
  700. self.lastEvent = event.type()
  701. return True
  702. else:
  703. self.lastEvent = event.type()
  704. return False
  705. class FCTabBar(QtWidgets.QTabBar):
  706. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  707. onMoveTabSignal = pyqtSignal(int, int)
  708. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  709. def __init__(self, parent=None):
  710. QtWidgets.QTabBar.__init__(self, parent)
  711. self.setAcceptDrops(True)
  712. self.setElideMode(QtCore.Qt.ElideRight)
  713. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  714. self.dragStartPos = QtCore.QPoint()
  715. self.dragDropedPos = QtCore.QPoint()
  716. self.mouseCursor = QtGui.QCursor()
  717. self.dragInitiated = False
  718. # Send the onDetachTabSignal when a tab is double clicked
  719. #
  720. # @param event a mouse double click event
  721. def mouseDoubleClickEvent(self, event):
  722. event.accept()
  723. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  724. # Set the starting position for a drag event when the mouse button is pressed
  725. #
  726. # @param event a mouse press event
  727. def mousePressEvent(self, event):
  728. if event.button() == QtCore.Qt.LeftButton:
  729. self.dragStartPos = event.pos()
  730. self.dragDropedPos.setX(0)
  731. self.dragDropedPos.setY(0)
  732. self.dragInitiated = False
  733. QtWidgets.QTabBar.mousePressEvent(self, event)
  734. # Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  735. # drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  736. # bar, emit an onDetachTabSignal.
  737. #
  738. # @param event a mouse move event
  739. def mouseMoveEvent(self, event):
  740. # Determine if the current movement is detected as a drag
  741. if not self.dragStartPos.isNull() and ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  742. self.dragInitiated = True
  743. # If the current movement is a drag initiated by the left button
  744. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  745. # Stop the move event
  746. finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier)
  747. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  748. # Convert the move event into a drag
  749. drag = QtGui.QDrag(self)
  750. mimeData = QtCore.QMimeData()
  751. # mimeData.setData('action', 'application/tab-detach')
  752. drag.setMimeData(mimeData)
  753. # screen = QScreen(self.parentWidget().currentWidget().winId())
  754. # Create the appearance of dragging the tab content
  755. try:
  756. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  757. except Exception as e:
  758. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  759. return
  760. targetPixmap = QtGui.QPixmap(pixmap.size())
  761. targetPixmap.fill(QtCore.Qt.transparent)
  762. painter = QtGui.QPainter(targetPixmap)
  763. painter.setOpacity(0.85)
  764. painter.drawPixmap(0, 0, pixmap)
  765. painter.end()
  766. drag.setPixmap(targetPixmap)
  767. # Initiate the drag
  768. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  769. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  770. # must be set manually
  771. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  772. dropAction = QtCore.Qt.MoveAction
  773. # If the drag completed outside of the tab bar, detach the tab and move
  774. # the content to the current cursor position
  775. if dropAction == QtCore.Qt.IgnoreAction:
  776. event.accept()
  777. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  778. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  779. elif dropAction == QtCore.Qt.MoveAction:
  780. if not self.dragDropedPos.isNull():
  781. event.accept()
  782. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  783. else:
  784. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  785. # Determine if the drag has entered a tab position from another tab position
  786. #
  787. # @param event a drag enter event
  788. def dragEnterEvent(self, event):
  789. mimeData = event.mimeData()
  790. # formats = mcd imeData.formats()
  791. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  792. # event.acceptProposedAction()
  793. QtWidgets.QTabBar.dragMoveEvent(self, event)
  794. # Get the position of the end of the drag
  795. #
  796. # @param event a drop event
  797. def dropEvent(self, event):
  798. self.dragDropedPos = event.pos()
  799. QtWidgets.QTabBar.dropEvent(self, event)
  800. # Determine if the detached tab drop event occurred on an existing tab,
  801. # then send the event to the DetachableTabWidget
  802. def detachedTabDrop(self, name, dropPos):
  803. tabDropPos = self.mapFromGlobal(dropPos)
  804. index = self.tabAt(tabDropPos)
  805. self.detachedTabDropSignal.emit(name, index, dropPos)
  806. class VerticalScrollArea(QtWidgets.QScrollArea):
  807. """
  808. This widget extends QtGui.QScrollArea to make a vertical-only
  809. scroll area that also expands horizontally to accomodate
  810. its contents.
  811. """
  812. def __init__(self, parent=None):
  813. QtWidgets.QScrollArea.__init__(self, parent=parent)
  814. self.setWidgetResizable(True)
  815. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  816. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  817. def eventFilter(self, source, event):
  818. """
  819. The event filter gets automatically installed when setWidget()
  820. is called.
  821. :param source:
  822. :param event:
  823. :return:
  824. """
  825. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  826. # log.debug("VerticalScrollArea: Widget resized:")
  827. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  828. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  829. self.setMinimumWidth(self.widget().sizeHint().width() +
  830. self.verticalScrollBar().sizeHint().width())
  831. # if self.verticalScrollBar().isVisible():
  832. # log.debug(" Scroll bar visible")
  833. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  834. # self.verticalScrollBar().width())
  835. # else:
  836. # log.debug(" Scroll bar hidden")
  837. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  838. return QtWidgets.QWidget.eventFilter(self, source, event)
  839. class OptionalInputSection:
  840. def __init__(self, cb, optinputs, logic=True):
  841. """
  842. Associates the a checkbox with a set of inputs.
  843. :param cb: Checkbox that enables the optional inputs.
  844. :param optinputs: List of widgets that are optional.
  845. :param logic: When True the logic is normal, when False the logic is in reverse
  846. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  847. for logic=False, when the checkbox is checked the widgets are Disabled
  848. :return:
  849. """
  850. assert isinstance(cb, FCCheckBox), \
  851. "Expected an FCCheckBox, got %s" % type(cb)
  852. self.cb = cb
  853. self.optinputs = optinputs
  854. self.logic = logic
  855. self.on_cb_change()
  856. self.cb.stateChanged.connect(self.on_cb_change)
  857. def on_cb_change(self):
  858. if self.cb.checkState():
  859. for widget in self.optinputs:
  860. if self.logic is True:
  861. widget.setEnabled(True)
  862. else:
  863. widget.setEnabled(False)
  864. else:
  865. for widget in self.optinputs:
  866. if self.logic is True:
  867. widget.setEnabled(False)
  868. else:
  869. widget.setEnabled(True)
  870. class FCTable(QtWidgets.QTableWidget):
  871. def __init__(self, parent=None):
  872. super(FCTable, self).__init__(parent)
  873. def sizeHint(self):
  874. default_hint_size = super(FCTable, self).sizeHint()
  875. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  876. def getHeight(self):
  877. height = self.horizontalHeader().height()
  878. for i in range(self.rowCount()):
  879. height += self.rowHeight(i)
  880. return height
  881. def getWidth(self):
  882. width = self.verticalHeader().width()
  883. for i in range(self.columnCount()):
  884. width += self.columnWidth(i)
  885. return width
  886. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  887. def setColortoRow(self, rowIndex, color):
  888. for j in range(self.columnCount()):
  889. self.item(rowIndex, j).setBackground(color)
  890. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  891. def mousePressEvent(self, event):
  892. if self.itemAt(event.pos()) is None:
  893. self.clearSelection()
  894. else:
  895. QtWidgets.QTableWidget.mousePressEvent(self, event)
  896. def setupContextMenu(self):
  897. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  898. def addContextMenu(self, entry, call_function, icon=None):
  899. action_name = str(entry)
  900. action = QtWidgets.QAction(self)
  901. action.setText(action_name)
  902. if icon:
  903. assert isinstance(icon, QtGui.QIcon), \
  904. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  905. action.setIcon(icon)
  906. self.addAction(action)
  907. action.triggered.connect(call_function)
  908. class FCSpinner(QtWidgets.QSpinBox):
  909. def __init__(self, parent=None):
  910. super(FCSpinner, self).__init__(parent)
  911. def get_value(self):
  912. return str(self.value())
  913. def set_value(self, val):
  914. try:
  915. k = int(val)
  916. except Exception as e:
  917. log.debug(str(e))
  918. return
  919. self.setValue(k)
  920. # def sizeHint(self):
  921. # default_hint_size = super(FCSpinner, self).sizeHint()
  922. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  923. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  924. def __init__(self, parent=None):
  925. super(FCDoubleSpinner, self).__init__(parent)
  926. self.readyToEdit = True
  927. def mousePressEvent(self, e, parent=None):
  928. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  929. if self.readyToEdit:
  930. self.lineEdit().selectAll()
  931. self.readyToEdit = False
  932. def focusOutEvent(self, e):
  933. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  934. self.lineEdit().deselect()
  935. self.readyToEdit = True
  936. def get_value(self):
  937. return str(self.value())
  938. def set_value(self, val):
  939. try:
  940. k = int(val)
  941. except Exception as e:
  942. log.debug(str(e))
  943. return
  944. self.setValue(k)
  945. def set_precision(self, val):
  946. self.setDecimals(val)
  947. def set_range(self, min_val, max_val):
  948. self.setRange(self, min_val, max_val)
  949. class Dialog_box(QtWidgets.QWidget):
  950. def __init__(self, title=None, label=None):
  951. """
  952. :param title: string with the window title
  953. :param label: string with the message inside the dialog box
  954. """
  955. super(Dialog_box, self).__init__()
  956. self.location = (0, 0)
  957. self.ok = False
  958. dialog_box = QtWidgets.QInputDialog()
  959. dialog_box.setFixedWidth(270)
  960. self.location, self.ok = dialog_box.getText(self, title, label)
  961. class _BrowserTextEdit(QTextEdit):
  962. def __init__(self, version):
  963. QTextEdit.__init__(self)
  964. self.menu = None
  965. self.version = version
  966. def contextMenuEvent(self, event):
  967. self.menu = self.createStandardContextMenu(event.pos())
  968. clear_action = QAction("Clear", self)
  969. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  970. self.menu.addAction(clear_action)
  971. clear_action.triggered.connect(self.clear)
  972. self.menu.exec_(event.globalPos())
  973. def clear(self):
  974. QTextEdit.clear(self)
  975. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  976. text = html.escape(text)
  977. text = text.replace('\n', '<br/>')
  978. self.moveCursor(QTextCursor.End)
  979. self.insertHtml(text)
  980. class _ExpandableTextEdit(QTextEdit):
  981. """
  982. Class implements edit line, which expands themselves automatically
  983. """
  984. historyNext = pyqtSignal()
  985. historyPrev = pyqtSignal()
  986. def __init__(self, termwidget, *args):
  987. QTextEdit.__init__(self, *args)
  988. self.setStyleSheet("font: 9pt \"Courier\";")
  989. self._fittedHeight = 1
  990. self.textChanged.connect(self._fit_to_document)
  991. self._fit_to_document()
  992. self._termWidget = termwidget
  993. self.completer = MyCompleter()
  994. self.model = QtCore.QStringListModel()
  995. self.completer.setModel(self.model)
  996. self.set_model_data(keyword_list=[])
  997. self.completer.insertText.connect(self.insertCompletion)
  998. def set_model_data(self, keyword_list):
  999. self.model.setStringList(keyword_list)
  1000. def insertCompletion(self, completion):
  1001. tc = self.textCursor()
  1002. extra = (len(completion) - len(self.completer.completionPrefix()))
  1003. tc.movePosition(QTextCursor.Left)
  1004. tc.movePosition(QTextCursor.EndOfWord)
  1005. tc.insertText(completion[-extra:])
  1006. self.setTextCursor(tc)
  1007. self.completer.popup().hide()
  1008. def focusInEvent(self, event):
  1009. if self.completer:
  1010. self.completer.setWidget(self)
  1011. QTextEdit.focusInEvent(self, event)
  1012. def keyPressEvent(self, event):
  1013. """
  1014. Catch keyboard events. Process Enter, Up, Down
  1015. """
  1016. if event.matches(QKeySequence.InsertParagraphSeparator):
  1017. text = self.toPlainText()
  1018. if self._termWidget.is_command_complete(text):
  1019. self._termWidget.exec_current_command()
  1020. return
  1021. elif event.matches(QKeySequence.MoveToNextLine):
  1022. text = self.toPlainText()
  1023. cursor_pos = self.textCursor().position()
  1024. textBeforeEnd = text[cursor_pos:]
  1025. if len(textBeforeEnd.split('\n')) <= 1:
  1026. self.historyNext.emit()
  1027. return
  1028. elif event.matches(QKeySequence.MoveToPreviousLine):
  1029. text = self.toPlainText()
  1030. cursor_pos = self.textCursor().position()
  1031. text_before_start = text[:cursor_pos]
  1032. # lineCount = len(textBeforeStart.splitlines())
  1033. line_count = len(text_before_start.split('\n'))
  1034. if len(text_before_start) > 0 and \
  1035. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1036. line_count += 1
  1037. if line_count <= 1:
  1038. self.historyPrev.emit()
  1039. return
  1040. elif event.matches(QKeySequence.MoveToNextPage) or \
  1041. event.matches(QKeySequence.MoveToPreviousPage):
  1042. return self._termWidget.browser().keyPressEvent(event)
  1043. tc = self.textCursor()
  1044. if event.key() == Qt.Key_Tab and self.completer.popup().isVisible():
  1045. self.completer.insertText.emit(self.completer.getSelected())
  1046. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1047. return
  1048. QTextEdit.keyPressEvent(self, event)
  1049. tc.select(QTextCursor.WordUnderCursor)
  1050. cr = self.cursorRect()
  1051. if len(tc.selectedText()) > 0:
  1052. self.completer.setCompletionPrefix(tc.selectedText())
  1053. popup = self.completer.popup()
  1054. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1055. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1056. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1057. self.completer.complete(cr)
  1058. else:
  1059. self.completer.popup().hide()
  1060. def sizeHint(self):
  1061. """
  1062. QWidget sizeHint impelemtation
  1063. """
  1064. hint = QTextEdit.sizeHint(self)
  1065. hint.setHeight(self._fittedHeight)
  1066. return hint
  1067. def _fit_to_document(self):
  1068. """
  1069. Update widget height to fit all text
  1070. """
  1071. documentsize = self.document().size().toSize()
  1072. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1073. self.setMaximumHeight(self._fittedHeight)
  1074. self.updateGeometry()
  1075. def insertFromMimeData(self, mime_data):
  1076. # Paste only plain text.
  1077. self.insertPlainText(mime_data.text())
  1078. class MyCompleter(QCompleter):
  1079. insertText = pyqtSignal(str)
  1080. def __init__(self, parent=None):
  1081. QCompleter.__init__(self)
  1082. self.setCompletionMode(QCompleter.PopupCompletion)
  1083. self.highlighted.connect(self.setHighlighted)
  1084. def setHighlighted(self, text):
  1085. self.lastSelected = text
  1086. def getSelected(self):
  1087. return self.lastSelected