uiparser.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. # Copyright (c) 2025 Riverbank Computing Limited.
  2. # Copyright (c) 2006 Thorsten Marek.
  3. # All right reserved.
  4. #
  5. # This file is part of PyQt.
  6. #
  7. # You may use this file under the terms of the GPL v3 or the revised BSD
  8. # license as follows:
  9. #
  10. # "Redistribution and use in source and binary forms, with or without
  11. # modification, are permitted provided that the following conditions are
  12. # met:
  13. # * Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # * Redistributions in binary form must reproduce the above copyright
  16. # notice, this list of conditions and the following disclaimer in
  17. # the documentation and/or other materials provided with the
  18. # distribution.
  19. # * Neither the name of the Riverbank Computing Limited nor the names
  20. # of its contributors may be used to endorse or promote products
  21. # derived from this software without specific prior written
  22. # permission.
  23. #
  24. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  27. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  28. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  29. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  30. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  31. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  32. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  35. import sys
  36. import logging
  37. import os
  38. import re
  39. from xml.etree.ElementTree import SubElement
  40. from .objcreator import QObjectCreator
  41. from .properties import Properties
  42. from .ui_file import UIFile
  43. logger = logging.getLogger(__name__)
  44. DEBUG = logger.debug
  45. QtCore = None
  46. QtGui = None
  47. QtWidgets = None
  48. def _parse_alignment(alignment):
  49. """ Convert a C++ alignment to the corresponding flags. """
  50. align_flags = None
  51. for qt_align in alignment.split('|'):
  52. *_, qt_align = qt_align.split('::')
  53. align = getattr(QtCore.Qt.AlignmentFlag, qt_align)
  54. if align_flags is None:
  55. align_flags = align
  56. else:
  57. align_flags |= align
  58. return align_flags
  59. def _layout_position(elem):
  60. """ Return either (), (0, alignment), (row, column, rowspan, colspan) or
  61. (row, column, rowspan, colspan, alignment) depending on the type of layout
  62. and its configuration. The result will be suitable to use as arguments to
  63. the layout.
  64. """
  65. row = elem.attrib.get('row')
  66. column = elem.attrib.get('column')
  67. alignment = elem.attrib.get('alignment')
  68. # See if it is a box layout.
  69. if row is None or column is None:
  70. if alignment is None:
  71. return ()
  72. return (0, _parse_alignment(alignment))
  73. # It must be a grid or a form layout.
  74. row = int(row)
  75. column = int(column)
  76. rowspan = int(elem.attrib.get('rowspan', 1))
  77. colspan = int(elem.attrib.get('colspan', 1))
  78. if alignment is None:
  79. return (row, column, rowspan, colspan)
  80. return (row, column, rowspan, colspan, _parse_alignment(alignment))
  81. class WidgetStack(list):
  82. topwidget = None
  83. def push(self, item):
  84. DEBUG("push %s %s" % (item.metaObject().className(),
  85. item.objectName()))
  86. self.append(item)
  87. if isinstance(item, QtWidgets.QWidget):
  88. self.topwidget = item
  89. def popLayout(self):
  90. layout = list.pop(self)
  91. DEBUG("pop layout %s %s" % (layout.metaObject().className(),
  92. layout.objectName()))
  93. return layout
  94. def popWidget(self):
  95. widget = list.pop(self)
  96. DEBUG("pop widget %s %s" % (widget.metaObject().className(),
  97. widget.objectName()))
  98. for item in reversed(self):
  99. if isinstance(item, QtWidgets.QWidget):
  100. self.topwidget = item
  101. break
  102. else:
  103. self.topwidget = None
  104. DEBUG("new topwidget %s" % (self.topwidget,))
  105. return widget
  106. def peek(self):
  107. return self[-1]
  108. def topIsLayout(self):
  109. return isinstance(self[-1], QtWidgets.QLayout)
  110. def topIsLayoutWidget(self):
  111. # A plain QWidget is a layout widget unless it's parent is a
  112. # QMainWindow or a container widget. Note that the corresponding uic
  113. # test is a little more complicated as it involves features not
  114. # supported by pyuic.
  115. if type(self[-1]) is not QtWidgets.QWidget:
  116. return False
  117. if len(self) < 2:
  118. return False
  119. parent = self[-2]
  120. return isinstance(parent, QtWidgets.QWidget) and type(parent) not in (
  121. QtWidgets.QMainWindow,
  122. QtWidgets.QStackedWidget,
  123. QtWidgets.QToolBox,
  124. QtWidgets.QTabWidget,
  125. QtWidgets.QScrollArea,
  126. QtWidgets.QMdiArea,
  127. QtWidgets.QWizard,
  128. QtWidgets.QDockWidget)
  129. class ButtonGroup(object):
  130. """ Encapsulate the configuration of a button group and its implementation.
  131. """
  132. def __init__(self):
  133. """ Initialise the button group. """
  134. self.exclusive = True
  135. self.object = None
  136. class UIParser(object):
  137. def __init__(self, qtcore_module, qtgui_module, qtwidgets_module, creatorPolicy):
  138. self.factory = QObjectCreator(creatorPolicy)
  139. self.wprops = Properties(self.factory, qtcore_module, qtgui_module,
  140. qtwidgets_module)
  141. global QtCore, QtGui, QtWidgets
  142. QtCore = qtcore_module
  143. QtGui = qtgui_module
  144. QtWidgets = qtwidgets_module
  145. self.reset()
  146. def uniqueName(self, name):
  147. """UIParser.uniqueName(string) -> string
  148. Create a unique name from a string.
  149. >>> p = UIParser(QtCore, QtGui, QtWidgets)
  150. >>> p.uniqueName("foo")
  151. 'foo'
  152. >>> p.uniqueName("foo")
  153. 'foo1'
  154. """
  155. try:
  156. suffix = self.name_suffixes[name]
  157. except KeyError:
  158. self.name_suffixes[name] = 0
  159. return name
  160. suffix += 1
  161. self.name_suffixes[name] = suffix
  162. return "%s%i" % (name, suffix)
  163. def reset(self):
  164. try: self.wprops.reset()
  165. except AttributeError: pass
  166. self.toplevelWidget = None
  167. self.stack = WidgetStack()
  168. self.name_suffixes = {}
  169. self.defaults = {'spacing': -1, 'margin': -1}
  170. self.actions = []
  171. self.currentActionGroup = None
  172. self.button_groups = {}
  173. def _setupObject(self, class_name, parent, branch, is_attribute=True,
  174. parent_is_optional=True):
  175. object_name = self.uniqueName(
  176. branch.attrib.get('name') or class_name[1:].lower())
  177. if parent is None:
  178. ctor_args = ()
  179. ctor_kwargs = {}
  180. elif parent_is_optional:
  181. ctor_args = ()
  182. ctor_kwargs = dict(parent=parent)
  183. else:
  184. ctor_args = (parent, )
  185. ctor_kwargs = {}
  186. obj = self.factory.createQtObject(class_name, object_name,
  187. ctor_args=ctor_args, ctor_kwargs=ctor_kwargs,
  188. is_attribute=is_attribute)
  189. self.wprops.setProperties(obj, branch)
  190. obj.setObjectName(object_name)
  191. if is_attribute:
  192. setattr(self.toplevelWidget, object_name, obj)
  193. return obj
  194. def getProperty(self, elem, name):
  195. for prop in elem.findall('property'):
  196. if prop.attrib['name'] == name:
  197. return prop
  198. return None
  199. def createWidget(self, elem):
  200. self.column_counter = 0
  201. self.row_counter = 0
  202. self.item_nr = 0
  203. self.itemstack = []
  204. self.sorting_enabled = None
  205. widget_class = elem.attrib['class'].replace('::', '.')
  206. if widget_class == 'Line':
  207. widget_class = 'QFrame'
  208. # Ignore the parent if it is a container.
  209. parent = self.stack.topwidget
  210. if isinstance(parent, (QtWidgets.QDockWidget, QtWidgets.QMdiArea,
  211. QtWidgets.QScrollArea, QtWidgets.QStackedWidget,
  212. QtWidgets.QToolBox, QtWidgets.QTabWidget,
  213. QtWidgets.QWizard)):
  214. parent = None
  215. self.stack.push(self._setupObject(widget_class, parent, elem))
  216. if isinstance(self.stack.topwidget, QtWidgets.QTableWidget):
  217. if self.getProperty(elem, 'columnCount') is None:
  218. self.stack.topwidget.setColumnCount(len(elem.findall("column")))
  219. if self.getProperty(elem, 'rowCount') is None:
  220. self.stack.topwidget.setRowCount(len(elem.findall("row")))
  221. self.traverseWidgetTree(elem)
  222. widget = self.stack.popWidget()
  223. if isinstance(widget, QtWidgets.QTreeView):
  224. self.handleHeaderView(elem, "header", widget.header())
  225. elif isinstance(widget, QtWidgets.QTableView):
  226. self.handleHeaderView(elem, "horizontalHeader",
  227. widget.horizontalHeader())
  228. self.handleHeaderView(elem, "verticalHeader",
  229. widget.verticalHeader())
  230. elif isinstance(widget, QtWidgets.QAbstractButton):
  231. bg_i18n = self.wprops.getAttribute(elem, "buttonGroup")
  232. if bg_i18n is not None:
  233. # This should be handled properly in case the problem arises
  234. # elsewhere as well.
  235. try:
  236. # We are compiling the .ui file.
  237. bg_name = bg_i18n.string
  238. except AttributeError:
  239. # We are loading the .ui file.
  240. bg_name = bg_i18n
  241. # Designer allows the creation of .ui files without explicit
  242. # button groups, even though uic then issues warnings. We
  243. # handle it in two stages by first making sure it has a name
  244. # and then making sure one exists with that name.
  245. if not bg_name:
  246. bg_name = 'buttonGroup'
  247. try:
  248. bg = self.button_groups[bg_name]
  249. except KeyError:
  250. bg = self.button_groups[bg_name] = ButtonGroup()
  251. if bg.object is None:
  252. bg.object = self.factory.createQtObject('QButtonGroup',
  253. bg_name, ctor_args=(self.toplevelWidget, ))
  254. setattr(self.toplevelWidget, bg_name, bg.object)
  255. bg.object.setObjectName(bg_name)
  256. if not bg.exclusive:
  257. bg.object.setExclusive(False)
  258. bg.object.addButton(widget)
  259. if self.sorting_enabled is not None:
  260. widget.setSortingEnabled(self.sorting_enabled)
  261. self.sorting_enabled = None
  262. if self.stack.topIsLayout():
  263. lay = self.stack.peek()
  264. lp = elem.attrib['layout-position']
  265. if isinstance(lay, QtWidgets.QFormLayout):
  266. lay.setWidget(lp[0], self._form_layout_role(lp), widget)
  267. else:
  268. lay.addWidget(widget, *lp)
  269. topwidget = self.stack.topwidget
  270. if isinstance(topwidget, QtWidgets.QToolBox):
  271. icon = self.wprops.getAttribute(elem, "icon")
  272. if icon is not None:
  273. topwidget.addItem(widget, icon, self.wprops.getAttribute(elem, "label"))
  274. else:
  275. topwidget.addItem(widget, self.wprops.getAttribute(elem, "label"))
  276. tooltip = self.wprops.getAttribute(elem, "toolTip")
  277. if tooltip is not None:
  278. topwidget.setItemToolTip(topwidget.indexOf(widget), tooltip)
  279. elif isinstance(topwidget, QtWidgets.QTabWidget):
  280. icon = self.wprops.getAttribute(elem, "icon")
  281. if icon is not None:
  282. topwidget.addTab(widget, icon, self.wprops.getAttribute(elem, "title"))
  283. else:
  284. topwidget.addTab(widget, self.wprops.getAttribute(elem, "title"))
  285. tooltip = self.wprops.getAttribute(elem, "toolTip")
  286. if tooltip is not None:
  287. topwidget.setTabToolTip(topwidget.indexOf(widget), tooltip)
  288. elif isinstance(topwidget, QtWidgets.QWizard):
  289. topwidget.addPage(widget)
  290. elif isinstance(topwidget, QtWidgets.QStackedWidget):
  291. topwidget.addWidget(widget)
  292. elif isinstance(topwidget, (QtWidgets.QDockWidget, QtWidgets.QScrollArea)):
  293. topwidget.setWidget(widget)
  294. elif isinstance(topwidget, QtWidgets.QMainWindow):
  295. if type(widget) == QtWidgets.QWidget:
  296. topwidget.setCentralWidget(widget)
  297. elif isinstance(widget, QtWidgets.QToolBar):
  298. tbArea = self.wprops.getAttribute(elem, "toolBarArea")
  299. if tbArea is None:
  300. topwidget.addToolBar(widget)
  301. else:
  302. topwidget.addToolBar(tbArea, widget)
  303. tbBreak = self.wprops.getAttribute(elem, "toolBarBreak")
  304. if tbBreak:
  305. topwidget.insertToolBarBreak(widget)
  306. elif isinstance(widget, QtWidgets.QMenuBar):
  307. topwidget.setMenuBar(widget)
  308. elif isinstance(widget, QtWidgets.QStatusBar):
  309. topwidget.setStatusBar(widget)
  310. elif isinstance(widget, QtWidgets.QDockWidget):
  311. dwArea = self.wprops.getAttribute(elem, "dockWidgetArea")
  312. topwidget.addDockWidget(QtCore.Qt.DockWidgetArea(dwArea),
  313. widget)
  314. def handleHeaderView(self, elem, name, header):
  315. value = self.wprops.getAttribute(elem, name + "Visible")
  316. if value is not None:
  317. header.setVisible(value)
  318. value = self.wprops.getAttribute(elem, name + "CascadingSectionResizes")
  319. if value is not None:
  320. header.setCascadingSectionResizes(value)
  321. value = self.wprops.getAttribute(elem, name + "DefaultSectionSize")
  322. if value is not None:
  323. header.setDefaultSectionSize(value)
  324. value = self.wprops.getAttribute(elem, name + "HighlightSections")
  325. if value is not None:
  326. header.setHighlightSections(value)
  327. value = self.wprops.getAttribute(elem, name + "MinimumSectionSize")
  328. if value is not None:
  329. header.setMinimumSectionSize(value)
  330. value = self.wprops.getAttribute(elem, name + "ShowSortIndicator")
  331. if value is not None:
  332. header.setSortIndicatorShown(value)
  333. value = self.wprops.getAttribute(elem, name + "StretchLastSection")
  334. if value is not None:
  335. header.setStretchLastSection(value)
  336. def createSpacer(self, elem):
  337. width = elem.findtext("property/size/width")
  338. height = elem.findtext("property/size/height")
  339. if width is None or height is None:
  340. size_args = ()
  341. else:
  342. size_args = (int(width), int(height))
  343. sizeType = self.wprops.getProperty(elem, "sizeType",
  344. QtWidgets.QSizePolicy.Policy.Expanding)
  345. policy = (QtWidgets.QSizePolicy.Policy.Minimum, sizeType)
  346. if self.wprops.getProperty(elem, "orientation") == QtCore.Qt.Orientation.Horizontal:
  347. policy = policy[1], policy[0]
  348. spacer = self.factory.createQtObject('QSpacerItem',
  349. self.uniqueName('spacerItem'), ctor_args=size_args + policy,
  350. is_attribute=False)
  351. if self.stack.topIsLayout():
  352. lay = self.stack.peek()
  353. lp = elem.attrib['layout-position']
  354. if isinstance(lay, QtWidgets.QFormLayout):
  355. lay.setItem(lp[0], self._form_layout_role(lp), spacer)
  356. else:
  357. lay.addItem(spacer, *lp)
  358. def createLayout(self, elem):
  359. # We use an internal property to handle margins which will use separate
  360. # left, top, right and bottom margins if they are found to be
  361. # different. The following will select, in order of preference,
  362. # separate margins, the same margin in all directions, and the default
  363. # margin.
  364. margin = -1 if self.stack.topIsLayout() else self.defaults['margin']
  365. margin = self.wprops.getProperty(elem, 'margin', margin)
  366. left = self.wprops.getProperty(elem, 'leftMargin', margin)
  367. top = self.wprops.getProperty(elem, 'topMargin', margin)
  368. right = self.wprops.getProperty(elem, 'rightMargin', margin)
  369. bottom = self.wprops.getProperty(elem, 'bottomMargin', margin)
  370. # A layout widget should, by default, have no margins.
  371. if self.stack.topIsLayoutWidget():
  372. if left < 0: left = 0
  373. if top < 0: top = 0
  374. if right < 0: right = 0
  375. if bottom < 0: bottom = 0
  376. if left >= 0 or top >= 0 or right >= 0 or bottom >= 0:
  377. # We inject the new internal property.
  378. cme = SubElement(elem, 'property', name='pyuicMargins')
  379. SubElement(cme, 'number').text = str(left)
  380. SubElement(cme, 'number').text = str(top)
  381. SubElement(cme, 'number').text = str(right)
  382. SubElement(cme, 'number').text = str(bottom)
  383. # We use an internal property to handle spacing which will use separate
  384. # horizontal and vertical spacing if they are found to be different.
  385. # The following will select, in order of preference, separate
  386. # horizontal and vertical spacing, the same spacing in both directions,
  387. # and the default spacing.
  388. spacing = self.wprops.getProperty(elem, 'spacing',
  389. self.defaults['spacing'])
  390. horiz = self.wprops.getProperty(elem, 'horizontalSpacing', spacing)
  391. vert = self.wprops.getProperty(elem, 'verticalSpacing', spacing)
  392. if horiz >= 0 or vert >= 0:
  393. # We inject the new internal property.
  394. cme = SubElement(elem, 'property', name='pyuicSpacing')
  395. SubElement(cme, 'number').text = str(horiz)
  396. SubElement(cme, 'number').text = str(vert)
  397. classname = elem.attrib["class"]
  398. if self.stack.topIsLayout():
  399. parent = None
  400. else:
  401. parent = self.stack.topwidget
  402. if "name" not in elem.attrib:
  403. elem.attrib["name"] = classname[1:].lower()
  404. self.stack.push(
  405. self._setupObject(classname, parent, elem,
  406. parent_is_optional=False))
  407. self.traverseWidgetTree(elem)
  408. layout = self.stack.popLayout()
  409. self.configureLayout(elem, layout)
  410. if self.stack.topIsLayout():
  411. top_layout = self.stack.peek()
  412. lp = elem.attrib['layout-position']
  413. if isinstance(top_layout, QtWidgets.QFormLayout):
  414. top_layout.setLayout(lp[0], self._form_layout_role(lp), layout)
  415. else:
  416. top_layout.addLayout(layout, *lp)
  417. def configureLayout(self, elem, layout):
  418. if isinstance(layout, QtWidgets.QGridLayout):
  419. self.setArray(elem, 'columnminimumwidth',
  420. layout.setColumnMinimumWidth)
  421. self.setArray(elem, 'rowminimumheight',
  422. layout.setRowMinimumHeight)
  423. self.setArray(elem, 'columnstretch', layout.setColumnStretch)
  424. self.setArray(elem, 'rowstretch', layout.setRowStretch)
  425. elif isinstance(layout, QtWidgets.QBoxLayout):
  426. self.setArray(elem, 'stretch', layout.setStretch)
  427. def setArray(self, elem, name, setter):
  428. array = elem.attrib.get(name)
  429. if array:
  430. for idx, value in enumerate(array.split(',')):
  431. value = int(value)
  432. if value > 0:
  433. setter(idx, value)
  434. def disableSorting(self, w):
  435. if self.item_nr == 0:
  436. self.sorting_enabled = self.factory.invoke("__sortingEnabled",
  437. w.isSortingEnabled)
  438. w.setSortingEnabled(False)
  439. def handleItem(self, elem):
  440. if self.stack.topIsLayout():
  441. elem[0].attrib['layout-position'] = _layout_position(elem)
  442. self.traverseWidgetTree(elem)
  443. else:
  444. w = self.stack.topwidget
  445. if isinstance(w, QtWidgets.QComboBox):
  446. text = self.wprops.getProperty(elem, "text")
  447. icon = self.wprops.getProperty(elem, "icon")
  448. if icon:
  449. w.addItem(icon, '')
  450. else:
  451. w.addItem('')
  452. w.setItemText(self.item_nr, text)
  453. elif isinstance(w, QtWidgets.QListWidget):
  454. self.disableSorting(w)
  455. item = self.createWidgetItem('QListWidgetItem', elem, w.item,
  456. self.item_nr)
  457. w.addItem(item)
  458. elif isinstance(w, QtWidgets.QTreeWidget):
  459. if self.itemstack:
  460. parent, _ = self.itemstack[-1]
  461. _, nr_in_root = self.itemstack[0]
  462. else:
  463. parent = w
  464. nr_in_root = self.item_nr
  465. item = self.factory.createQtObject('QTreeWidgetItem',
  466. 'item_%d' % len(self.itemstack), ctor_args=(parent, ),
  467. is_attribute=False)
  468. if self.item_nr == 0 and not self.itemstack:
  469. self.sorting_enabled = self.factory.invoke("__sortingEnabled", w.isSortingEnabled)
  470. w.setSortingEnabled(False)
  471. self.itemstack.append((item, self.item_nr))
  472. self.item_nr = 0
  473. # We have to access the item via the tree when setting the
  474. # text.
  475. titm = w.topLevelItem(nr_in_root)
  476. for child, nr_in_parent in self.itemstack[1:]:
  477. titm = titm.child(nr_in_parent)
  478. column = -1
  479. for prop in elem.findall('property'):
  480. c_prop = self.wprops.convert(prop)
  481. c_prop_name = prop.attrib['name']
  482. if c_prop_name == 'text':
  483. column += 1
  484. if c_prop:
  485. titm.setText(column, c_prop)
  486. elif c_prop_name == 'statusTip':
  487. item.setStatusTip(column, c_prop)
  488. elif c_prop_name == 'toolTip':
  489. item.setToolTip(column, c_prop)
  490. elif c_prop_name == 'whatsThis':
  491. item.setWhatsThis(column, c_prop)
  492. elif c_prop_name == 'font':
  493. item.setFont(column, c_prop)
  494. elif c_prop_name == 'icon':
  495. item.setIcon(column, c_prop)
  496. elif c_prop_name == 'background':
  497. item.setBackground(column, c_prop)
  498. elif c_prop_name == 'foreground':
  499. item.setForeground(column, c_prop)
  500. elif c_prop_name == 'flags':
  501. item.setFlags(c_prop)
  502. elif c_prop_name == 'checkState':
  503. item.setCheckState(column, c_prop)
  504. self.traverseWidgetTree(elem)
  505. _, self.item_nr = self.itemstack.pop()
  506. elif isinstance(w, QtWidgets.QTableWidget):
  507. row = int(elem.attrib['row'])
  508. col = int(elem.attrib['column'])
  509. self.disableSorting(w)
  510. item = self.createWidgetItem('QTableWidgetItem', elem, w.item,
  511. row, col)
  512. w.setItem(row, col, item)
  513. self.item_nr += 1
  514. def addAction(self, elem):
  515. self.actions.append((self.stack.topwidget, elem.attrib["name"]))
  516. @staticmethod
  517. def any_i18n(*args):
  518. """ Return True if any argument appears to be an i18n string. """
  519. for a in args:
  520. if a is not None and not isinstance(a, str):
  521. return True
  522. return False
  523. def createWidgetItem(self, item_type, elem, getter, *getter_args):
  524. """ Create a specific type of widget item. """
  525. item = self.factory.createQtObject(item_type, 'item',
  526. is_attribute=False)
  527. props = self.wprops
  528. # Note that not all types of widget items support the full set of
  529. # properties.
  530. text = props.getProperty(elem, 'text')
  531. status_tip = props.getProperty(elem, 'statusTip')
  532. tool_tip = props.getProperty(elem, 'toolTip')
  533. whats_this = props.getProperty(elem, 'whatsThis')
  534. if self.any_i18n(text, status_tip, tool_tip, whats_this):
  535. self.factory.invoke("item", getter, getter_args)
  536. if text:
  537. item.setText(text)
  538. if status_tip:
  539. item.setStatusTip(status_tip)
  540. if tool_tip:
  541. item.setToolTip(tool_tip)
  542. if whats_this:
  543. item.setWhatsThis(whats_this)
  544. text_alignment = props.getProperty(elem, 'textAlignment')
  545. if text_alignment:
  546. item.setTextAlignment(text_alignment)
  547. font = props.getProperty(elem, 'font')
  548. if font:
  549. item.setFont(font)
  550. icon = props.getProperty(elem, 'icon')
  551. if icon:
  552. item.setIcon(icon)
  553. background = props.getProperty(elem, 'background')
  554. if background:
  555. item.setBackground(background)
  556. foreground = props.getProperty(elem, 'foreground')
  557. if foreground:
  558. item.setForeground(foreground)
  559. flags = props.getProperty(elem, 'flags')
  560. if flags:
  561. item.setFlags(flags)
  562. check_state = props.getProperty(elem, 'checkState')
  563. if check_state:
  564. item.setCheckState(check_state)
  565. return item
  566. def addHeader(self, elem):
  567. w = self.stack.topwidget
  568. if isinstance(w, QtWidgets.QTreeWidget):
  569. props = self.wprops
  570. col = self.column_counter
  571. text = props.getProperty(elem, 'text')
  572. if text:
  573. w.headerItem().setText(col, text)
  574. status_tip = props.getProperty(elem, 'statusTip')
  575. if status_tip:
  576. w.headerItem().setStatusTip(col, status_tip)
  577. tool_tip = props.getProperty(elem, 'toolTip')
  578. if tool_tip:
  579. w.headerItem().setToolTip(col, tool_tip)
  580. whats_this = props.getProperty(elem, 'whatsThis')
  581. if whats_this:
  582. w.headerItem().setWhatsThis(col, whats_this)
  583. text_alignment = props.getProperty(elem, 'textAlignment')
  584. if text_alignment:
  585. w.headerItem().setTextAlignment(col, text_alignment)
  586. font = props.getProperty(elem, 'font')
  587. if font:
  588. w.headerItem().setFont(col, font)
  589. icon = props.getProperty(elem, 'icon')
  590. if icon:
  591. w.headerItem().setIcon(col, icon)
  592. background = props.getProperty(elem, 'background')
  593. if background:
  594. w.headerItem().setBackground(col, background)
  595. foreground = props.getProperty(elem, 'foreground')
  596. if foreground:
  597. w.headerItem().setForeground(col, foreground)
  598. self.column_counter += 1
  599. elif isinstance(w, QtWidgets.QTableWidget):
  600. if len(elem) != 0:
  601. if elem.tag == 'column':
  602. item = self.createWidgetItem('QTableWidgetItem', elem,
  603. w.horizontalHeaderItem, self.column_counter)
  604. w.setHorizontalHeaderItem(self.column_counter, item)
  605. self.column_counter += 1
  606. elif elem.tag == 'row':
  607. item = self.createWidgetItem('QTableWidgetItem', elem,
  608. w.verticalHeaderItem, self.row_counter)
  609. w.setVerticalHeaderItem(self.row_counter, item)
  610. self.row_counter += 1
  611. def setZOrder(self, elem):
  612. # Designer can generate empty zorder elements.
  613. if elem.text is None:
  614. return
  615. # Designer allows the z-order of spacer items to be specified even
  616. # though they can't be raised, so ignore any missing raise_() method.
  617. try:
  618. getattr(self.toplevelWidget, elem.text).raise_()
  619. except AttributeError:
  620. # Note that uic issues a warning message.
  621. pass
  622. def createAction(self, elem):
  623. self._setupObject('QAction',
  624. self.currentActionGroup or self.toplevelWidget, elem)
  625. def createActionGroup(self, elem):
  626. action_group = self._setupObject('QActionGroup', self.toplevelWidget,
  627. elem, parent_is_optional=False)
  628. self.currentActionGroup = action_group
  629. self.traverseWidgetTree(elem)
  630. self.currentActionGroup = None
  631. widgetTreeItemHandlers = {
  632. "widget" : createWidget,
  633. "addaction" : addAction,
  634. "layout" : createLayout,
  635. "spacer" : createSpacer,
  636. "item" : handleItem,
  637. "action" : createAction,
  638. "actiongroup": createActionGroup,
  639. "column" : addHeader,
  640. "row" : addHeader,
  641. "zorder" : setZOrder,
  642. }
  643. def traverseWidgetTree(self, elem):
  644. for child in iter(elem):
  645. try:
  646. handler = self.widgetTreeItemHandlers[child.tag]
  647. except KeyError:
  648. continue
  649. handler(self, child)
  650. def _handle_widget(self, el):
  651. """ Handle the top-level <widget> element. """
  652. # Get the names of the class and widget.
  653. cname = el.attrib["class"]
  654. wname = el.attrib["name"]
  655. # If there was no widget name then derive it from the class name.
  656. if not wname:
  657. wname = cname
  658. if wname.startswith("Q"):
  659. wname = wname[1:]
  660. wname = wname[0].lower() + wname[1:]
  661. self.toplevelWidget = self.createToplevelWidget(cname, wname)
  662. self.toplevelWidget.setObjectName(wname)
  663. DEBUG("toplevel widget is %s",
  664. self.toplevelWidget.metaObject().className())
  665. self.wprops.setProperties(self.toplevelWidget, el)
  666. self.stack.push(self.toplevelWidget)
  667. self.traverseWidgetTree(el)
  668. self.stack.popWidget()
  669. self.addActions()
  670. self.setBuddies()
  671. self.setDelayedProps()
  672. def addActions(self):
  673. for widget, action_name in self.actions:
  674. if action_name == "separator":
  675. widget.addSeparator()
  676. else:
  677. DEBUG("add action %s to %s", action_name, widget.objectName())
  678. action_obj = getattr(self.toplevelWidget, action_name)
  679. if isinstance(action_obj, QtWidgets.QMenu):
  680. widget.addAction(action_obj.menuAction())
  681. elif not isinstance(action_obj, QtGui.QActionGroup):
  682. widget.addAction(action_obj)
  683. def setDelayedProps(self):
  684. for widget, layout, setter, args in self.wprops.delayed_props:
  685. if layout:
  686. widget = widget.layout()
  687. setter = getattr(widget, setter)
  688. setter(args)
  689. def setBuddies(self):
  690. for widget, buddy in self.wprops.buddies:
  691. DEBUG("%s is buddy of %s", buddy, widget.objectName())
  692. try:
  693. widget.setBuddy(getattr(self.toplevelWidget, buddy))
  694. except AttributeError:
  695. DEBUG("ERROR in ui spec: %s (buddy of %s) does not exist",
  696. buddy, widget.objectName())
  697. def setContext(self, context):
  698. """
  699. Reimplemented by a sub-class if it needs to know the translation
  700. context.
  701. """
  702. pass
  703. def _handle_layout_default(self, el):
  704. """ Handle the <layoutdefault> element. """
  705. self.defaults['margin'] = int(el.attrib['margin'])
  706. self.defaults['spacing'] = int(el.attrib['spacing'])
  707. def _handle_tab_stops(self, el):
  708. """ Handle the <tabstops> element. """
  709. lastwidget = None
  710. for widget_el in el:
  711. widget = getattr(self.toplevelWidget, widget_el.text)
  712. if lastwidget is not None:
  713. self.toplevelWidget.setTabOrder(lastwidget, widget)
  714. lastwidget = widget
  715. def _handle_connections(self, el):
  716. """ Handle the <connections> element. """
  717. def name2object(obj):
  718. if obj == self.uiname:
  719. return self.toplevelWidget
  720. else:
  721. return getattr(self.toplevelWidget, obj)
  722. for conn in el:
  723. signal = conn.findtext('signal')
  724. signal_name, signal_args = signal.split('(')
  725. signal_args = signal_args[:-1].replace(' ', '')
  726. sender = name2object(conn.findtext('sender'))
  727. bound_signal = getattr(sender, signal_name)
  728. slot = self.factory.getSlot(name2object(conn.findtext('receiver')),
  729. conn.findtext('slot').split('(')[0])
  730. if signal_args == '':
  731. bound_signal.connect(slot)
  732. else:
  733. signal_args = signal_args.split(',')
  734. if len(signal_args) == 1:
  735. bound_signal[signal_args[0]].connect(slot)
  736. else:
  737. bound_signal[tuple(signal_args)].connect(slot)
  738. QtCore.QMetaObject.connectSlotsByName(self.toplevelWidget)
  739. def _handle_custom_widgets(self, el):
  740. """ Handle the <customwidgets> element. """
  741. def header2module(header):
  742. """header2module(header) -> string
  743. Convert paths to C++ header files to according Python modules
  744. >>> header2module("foo/bar/baz.h")
  745. 'foo.bar.baz'
  746. """
  747. if header.endswith(".h"):
  748. header = header[:-2]
  749. mpath = []
  750. for part in header.split('/'):
  751. # Ignore any empty parts or those that refer to the current
  752. # directory.
  753. if part not in ('', '.'):
  754. if part == '..':
  755. # We should allow this for Python3.
  756. raise SyntaxError("custom widget header file name may not contain '..'.")
  757. mpath.append(part)
  758. return '.'.join(mpath)
  759. for custom_widget in el:
  760. classname = custom_widget.findtext("class")
  761. self.factory.addCustomWidget(classname,
  762. custom_widget.findtext("extends") or "QWidget",
  763. header2module(custom_widget.findtext("header")))
  764. def createToplevelWidget(self, classname, widgetname):
  765. raise NotImplementedError
  766. def _handle_button_groups(self, el):
  767. """ Handle the <buttongroups> element. """
  768. for button_group in el:
  769. if button_group.tag == 'buttongroup':
  770. bg_name = button_group.attrib['name']
  771. bg = ButtonGroup()
  772. self.button_groups[bg_name] = bg
  773. prop = self.getProperty(button_group, 'exclusive')
  774. if prop is not None:
  775. if prop.findtext('bool') == 'false':
  776. bg.exclusive = False
  777. # finalize will be called after the whole tree has been parsed and can be
  778. # overridden.
  779. def finalize(self):
  780. pass
  781. def parse(self, filename):
  782. if hasattr(filename, 'read'):
  783. base_dir = ''
  784. else:
  785. base_dir = os.path.dirname(filename)
  786. self.wprops.set_base_dir(base_dir)
  787. ui_file = UIFile(filename)
  788. self.uiname = ui_file.class_name
  789. self.wprops.uiname = ui_file.class_name
  790. self.setContext(ui_file.class_name)
  791. # The order in which the elements are handled is important. The widget
  792. # handler relies on all custom widgets being known, and in order to
  793. # create the connections, all widgets have to be populated.
  794. if ui_file.layout_default is not None:
  795. self._handle_layout_default(ui_file.layout_default)
  796. if ui_file.button_groups is not None:
  797. self._handle_button_groups(ui_file.button_groups)
  798. if ui_file.custom_widgets is not None:
  799. self._handle_custom_widgets(ui_file.custom_widgets)
  800. if ui_file.widget is not None:
  801. self._handle_widget(ui_file.widget)
  802. if ui_file.connections is not None:
  803. self._handle_connections(ui_file.connections)
  804. if ui_file.tab_stops is not None:
  805. self._handle_tab_stops(ui_file.tab_stops)
  806. self.finalize()
  807. w = self.toplevelWidget
  808. self.reset()
  809. return w
  810. @staticmethod
  811. def _form_layout_role(layout_position):
  812. if layout_position[3] > 1:
  813. role = QtWidgets.QFormLayout.ItemRole.SpanningRole
  814. elif layout_position[1] == 1:
  815. role = QtWidgets.QFormLayout.ItemRole.FieldRole
  816. else:
  817. role = QtWidgets.QFormLayout.ItemRole.LabelRole
  818. return role