#############################################################################
##
## Copyright (C) 2019 Riverbank Computing Limited.
## Copyright (C) 2006 Thorsten Marek.
## All right reserved.
##
## This file is part of PyQt.
##
## You may use this file under the terms of the GPL v2 or the revised BSD
## license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of the Riverbank Computing Limited nor the names
## of its contributors may be used to endorse or promote products
## derived from this software without specific prior written
## permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
#############################################################################
import sys
import logging
import os
import re
from xml.etree.ElementTree import parse, SubElement
from .objcreator import QObjectCreator
from .properties import Properties
logger = logging.getLogger(__name__)
DEBUG = logger.debug
QtCore = None
QtWidgets = None
def _parse_alignment(alignment):
""" Convert a C++ alignment to the corresponding flags. """
align_flags = None
for qt_align in alignment.split('|'):
_, qt_align = qt_align.split('::')
align = getattr(QtCore.Qt, qt_align)
if align_flags is None:
align_flags = align
else:
align_flags |= align
return align_flags
def _layout_position(elem):
""" Return either (), (0, alignment), (row, column, rowspan, colspan) or
(row, column, rowspan, colspan, alignment) depending on the type of layout
and its configuration. The result will be suitable to use as arguments to
the layout.
"""
row = elem.attrib.get('row')
column = elem.attrib.get('column')
alignment = elem.attrib.get('alignment')
# See if it is a box layout.
if row is None or column is None:
if alignment is None:
return ()
return (0, _parse_alignment(alignment))
# It must be a grid or a form layout.
row = int(row)
column = int(column)
rowspan = int(elem.attrib.get('rowspan', 1))
colspan = int(elem.attrib.get('colspan', 1))
if alignment is None:
return (row, column, rowspan, colspan)
return (row, column, rowspan, colspan, _parse_alignment(alignment))
class WidgetStack(list):
topwidget = None
def push(self, item):
DEBUG("push %s %s" % (item.metaObject().className(),
item.objectName()))
self.append(item)
if isinstance(item, QtWidgets.QWidget):
self.topwidget = item
def popLayout(self):
layout = list.pop(self)
DEBUG("pop layout %s %s" % (layout.metaObject().className(),
layout.objectName()))
return layout
def popWidget(self):
widget = list.pop(self)
DEBUG("pop widget %s %s" % (widget.metaObject().className(),
widget.objectName()))
for item in reversed(self):
if isinstance(item, QtWidgets.QWidget):
self.topwidget = item
break
else:
self.topwidget = None
DEBUG("new topwidget %s" % (self.topwidget,))
return widget
def peek(self):
return self[-1]
def topIsLayout(self):
return isinstance(self[-1], QtWidgets.QLayout)
def topIsLayoutWidget(self):
# A plain QWidget is a layout widget unless it's parent is a
# QMainWindow or a container widget. Note that the corresponding uic
# test is a little more complicated as it involves features not
# supported by pyuic.
if type(self[-1]) is not QtWidgets.QWidget:
return False
if len(self) < 2:
return False
parent = self[-2]
return isinstance(parent, QtWidgets.QWidget) and type(parent) not in (
QtWidgets.QMainWindow,
QtWidgets.QStackedWidget,
QtWidgets.QToolBox,
QtWidgets.QTabWidget,
QtWidgets.QScrollArea,
QtWidgets.QMdiArea,
QtWidgets.QWizard,
QtWidgets.QDockWidget)
class ButtonGroup(object):
""" Encapsulate the configuration of a button group and its implementation.
"""
def __init__(self):
""" Initialise the button group. """
self.exclusive = True
self.object = None
class UIParser(object):
def __init__(self, qtcore_module, qtgui_module, qtwidgets_module, creatorPolicy):
self.factory = QObjectCreator(creatorPolicy)
self.wprops = Properties(self.factory, qtcore_module, qtgui_module,
qtwidgets_module)
global QtCore, QtWidgets
QtCore = qtcore_module
QtWidgets = qtwidgets_module
self.reset()
def uniqueName(self, name):
"""UIParser.uniqueName(string) -> string
Create a unique name from a string.
>>> p = UIParser(QtCore, QtGui, QtWidgets)
>>> p.uniqueName("foo")
'foo'
>>> p.uniqueName("foo")
'foo1'
"""
try:
suffix = self.name_suffixes[name]
except KeyError:
self.name_suffixes[name] = 0
return name
suffix += 1
self.name_suffixes[name] = suffix
return "%s%i" % (name, suffix)
def reset(self):
try: self.wprops.reset()
except AttributeError: pass
self.toplevelWidget = None
self.stack = WidgetStack()
self.name_suffixes = {}
self.defaults = {'spacing': -1, 'margin': -1}
self.actions = []
self.currentActionGroup = None
self.resources = []
self.button_groups = {}
def setupObject(self, clsname, parent, branch, is_attribute=True):
name = self.uniqueName(branch.attrib.get('name') or clsname[1:].lower())
if parent is None:
args = ()
else:
args = (parent, )
obj = self.factory.createQObject(clsname, name, args, is_attribute)
self.wprops.setProperties(obj, branch)
obj.setObjectName(name)
if is_attribute:
setattr(self.toplevelWidget, name, obj)
return obj
def getProperty(self, elem, name):
for prop in elem.findall('property'):
if prop.attrib['name'] == name:
return prop
return None
def createWidget(self, elem):
self.column_counter = 0
self.row_counter = 0
self.item_nr = 0
self.itemstack = []
self.sorting_enabled = None
widget_class = elem.attrib['class'].replace('::', '.')
if widget_class == 'Line':
widget_class = 'QFrame'