Пример #1
0
def storePixmap(pixmap, filetype='PNG'):
    import_qt(globals())

    arr = QtCore.QByteArray()
    buf = QtCore.QBuffer()
    buf.setBuffer(arr)
    buf.open(QtCore.QBuffer.WriteOnly)
    pixmap.save(buf, filetype)
    buf.close()

    return binascii.b2a_base64(nativestring(arr))
Пример #2
0
    def listdir(self, relpath, rsc=None):
        """
        Returns a list of the files within a path.  When compiled, it will
        list the files within a QResource, otherwise will list the files
        within the directory.
        
        :param      relpath | <str>
                    rsc     | <str> || None
        
        :return     [<str>, ..]
        """
        filepath = self.find(relpath, rsc)

        # parse a resource object
        if filepath.startswith(':'):
            resource = QtCore.QResource(filepath)

            # load the resource
            return map(str, resource.children())

        # parse a filepath
        elif os.path.isdir(filepath):
            return os.listdir(filepath)

        return []
Пример #3
0
    def systemSettings(self):
        """
        Returns the settings associated with this application for all users.
        
        :return     <projexui.xsettings.XSettings>
        """
        if not self._systemSettings:
            if self.isCompiled():
                settings = QtCore.QSettings(XSettings.IniFormat,
                                            XSettings.SystemScope,
                                            self.organizationName(),
                                            self.applicationName())
                rootpath = os.path.dirname(settings.fileName())
            else:
                rootpath = os.path.abspath('.')

            name = self.applicationName()
            filename = os.path.join(rootpath, '{0}.yaml'.format(name))

            self._systemSettings = XSettings(XSettings.YamlFormat,
                                             XSettings.SystemScope,
                                             self.organizationName(),
                                             self.applicationName(),
                                             filename=filename)

        return self._systemSettings
Пример #4
0
    def highlightBlock(self, text):
        """
        Highlights the given text format based on this highlighters syntax
        rules.
        
        :param      text | <str>
        """
        text = nativestring(text)
        for pattern, format in self.patterns():
            for result in re.finditer(pattern, text):
                grps = result.groups()
                if grps:
                    for i in range(len(grps)):
                        start, end = result.span(i+1)
                        self.setFormat(start, end - start, format)
                else:
                    self.setFormat(result.start(),
                                   result.end() - result.start(),
                                   format)
        
        self.setCurrentBlockState(0)
        if self.previousBlockState() == 1:
            return
        
        for form, open, close in self._multiline:
            open = QtCore.QRegExp(open)
            close = QtCore.QRegExp(close)
            
            start = open.indexIn(text)
            processed = False
            
            while start >= 0:
                processed = True
                end = close.indexIn(text, start)

                if end == -1:
                    self.setCurrentBlockState(1)
                    length = len(text) - start
                else:
                    length = end - start + close.matchedLength()

                self.setFormat(start, length, form)
                start = open.indexIn(text, start + length)
            
            if processed:
                break
Пример #5
0
    def restoreValue(self, xelem):
        """
        Stores the value for the inptued instance to the given xml element.
        
        :param      xelem | <xml.etree.Element>
        
        :return     <variant>
        """
        typ = xelem.get('type')

        if typ == 'color':
            return QtGui.QColor(xelem.text)

        elif typ == 'point':
            return QtCore.QPoint(*map(int, xelem.text.split(',')))

        elif typ == 'pointf':
            return QtCore.QPointF(*map(float, xelem.text.split(',')))

        elif typ == 'rect':
            return QtCore.QRectF(*map(int, xelem.text.split(',')))

        elif typ == 'rectf':
            return QtCore.QRectF(*map(float, xelem.text.split(',')))

        elif typ == 'bytea':
            return QtCore.QByteArray(cPickle.loads(xelem.text))

        elif typ == 'pickle':
            return cPickle.loads(xelem.text)

        elif typ == 'xml':
            return xelem[0]

        elif typ in ('str', 'unicode'):
            return xelem.text

        else:
            try:
                return eval('{0}({1})'.format(typ, xelem.text))
            except:
                return None
Пример #6
0
 def __init__(self, parent=None):
     super(XWalkthroughGraphic, self).__init__(parent)
     
     # define custom properties
     self._properties = {}
     self._parsers = {}
     
     # define parser system
     self._parsers['align'] = lambda x: alignments.get(x, QtCore.Qt.AlignCenter)
     self._parsers['pos'] = lambda x: QtCore.QPoint(*map(int, x.split()))
     self._parsers['offset'] = lambda x: QtCore.QPointF(*map(float, x.split()))
     self._parsers['crop'] = lambda x: QtCore.QRect(*map(int, x.split()))
     self._parsers['scaled'] = lambda x: float(x)
     self._parsers['direction'] = lambda x: getattr(QtGui.QBoxLayout,
                                                    x,
                                                    QtGui.QBoxLayout.TopToBottom)
     
     # define default options
     self.setProperty('direction', QtGui.QBoxLayout.TopToBottom)
     self.setProperty('align', QtCore.Qt.AlignCenter)
Пример #7
0
 def isfile(self, relpath, rsc=None):
     """
     Returns whether or not the resource is a directory.
     
     :return     <bool>
     """
     filepath = self.find(relpath, rsc)
     if filepath.startswith(':'):
         resource = QtCore.QResource(filepath)
         return resource.isFile() and resource.isValid()
     else:
         return os.path.isfile(filepath)
Пример #8
0
    def exists(self, relpath, rsc=None, useFilepath=None):
        """
        Checks to see if the inputed path represents an existing file or directory.

        :param      relpath     | <str>
                    rsc         | <str>
                    useFilepath | <bool> or None
        """
        path = self.find(relpath, rsc, useFilepath)
        if path.startswith(':'):
            return QtCore.QResource(path).isValid()
        else:
            return os.path.exists(path)
Пример #9
0
    def load(self, relpath, rsc=None, mode='r', useFilepath=None):
        """
        Opens a file like object for reading for the given relpath.
        
        :param      relpath | <str>
        
        :return     <File> || <QFile> || None
        """
        filepath = self.find(relpath, rsc, useFilepath=useFilepath)

        # parse a resource object
        if filepath.startswith(':'):
            return QtCore.QFile(filepath)

        # parse a filepath
        elif os.path.isfile(filepath):
            return open(filepath, mode)

        # return an unknown object
        else:
            return None
Пример #10
0
 def prepare(self):
     """
     Prepares the information for this graphic.
     """
     # determine if we already have a snapshot setup
     pixmap = self.property('pixmap')
     if pixmap is not None:
         return super(XWalkthroughSnapshot, self).prepare()
     
     # otherwise, setup the snapshot
     widget = self.property('widget')
     if type(widget) in (unicode, str):
         widget = self.findReference(widget)
         if not widget:
             return super(XWalkthroughSnapshot, self).prepare()
     
     # test if this is an overlay option
     if self.property('overlay') and widget.parent():
         ref = self.referenceWidget()
         if ref == widget:
             pos = QtCore.QPoint(0, 0)
         else:
             glbl_pos = widget.mapToGlobal(QtCore.QPoint(0, 0))
             pos = ref.mapFromGlobal(glbl_pos)
         
         self.setProperty('pos', pos)
     
     # crop out the options
     crop = self.property('crop', QtCore.QRect(0, 0, 0, 0))
     
     if crop:
         rect = widget.rect()
         if crop.width():
             rect.setWidth(crop.width())
         if crop.height():
             rect.setHeight(crop.height())
         if crop.x():
             rect.setX(rect.width() - crop.x())
         if crop.y():
             rect.setY(rect.height() - crop.y())
         
         pixmap = QtGui.QPixmap.grabWidget(widget, rect)
     else:
         pixmap = QtGui.QPixmap.grabWidget(widget)
     
     scaled = self.property('scaled')
     if scaled:
         pixmap = pixmap.scaled(pixmap.width() * scaled,
                                pixmap.height() * scaled,
                                QtCore.Qt.KeepAspectRatio,
                                QtCore.Qt.SmoothTransformation)
     
     kwds = {}
     kwds['whatsThis'] = widget.whatsThis()
     kwds['toolTip'] = widget.toolTip()
     kwds['windowTitle'] = widget.windowTitle()
     kwds['objectName'] = widget.objectName()
     
     self.setProperty('caption', self.property('caption', '').format(**kwds))
     self.setProperty('pixmap', pixmap)
     self.addPixmap(pixmap)
     
     return super(XWalkthroughSnapshot, self).prepare()
Пример #11
0
    def __init__(self, parent, windowFlags=0):
        windowFlags = QtCore.Qt.WindowFlags(windowFlags)
        super(XMdiSubWindow, self).__init__(parent, windowFlags)

        # define custom properties
        palette = self.palette()

        font = self.font()
        font.setBold(True)
        font.setPointSize(font.pointSize() + 2)

        self._titleBarFont = font
        self._titleBarBackground = palette.color(palette.Button)
        self._titleBarForeground = palette.color(palette.ButtonText)
        self._titleBarBorder = QtGui.QColor('black')

        # create the drop shadow effect
        eff = QtGui.QGraphicsDropShadowEffect(self)
        eff.setOffset(0, 0)
        eff.setBlurRadius(40)
        eff.setColor(palette.color(palette.Shadow))
        self.setGraphicsEffect(eff)

        # create the control buttons
        self._sysmenuBtn = XToolButton(self)
        self._sysmenuBtn.setIcon(self.windowIcon())
        self._sysmenuBtn.setPalette(palette)
        self._sysmenuBtn.setAutoRaise(True)
        self._sysmenuBtn.setFixedSize(QtCore.QSize(22, 22))
        self._sysmenuBtn.move(4, 4)
        self._sysmenuBtn.show()

        palette.setColor(palette.Shadow, QtGui.QColor('yellow'))

        self._minimizeBtn = XToolButton(self)
        self._minimizeBtn.setIcon(
            QtGui.QIcon(resources.find('img/mdiarea/minimize.png')))
        self._minimizeBtn.setPalette(palette)
        self._minimizeBtn.setShadowed(True)
        self._minimizeBtn.setShadowRadius(10)
        self._minimizeBtn.setFixedSize(QtCore.QSize(22, 22))
        self._minimizeBtn.show()

        palette.setColor(palette.Shadow, QtGui.QColor('orange'))

        self._maximizeBtn = XToolButton(self)
        self._maximizeBtn.setIcon(
            QtGui.QIcon(resources.find('img/mdiarea/maximize.png')))
        self._maximizeBtn.setPalette(palette)
        self._maximizeBtn.setShadowed(True)
        self._maximizeBtn.setShadowRadius(10)
        self._maximizeBtn.setFixedSize(QtCore.QSize(22, 22))
        self._maximizeBtn.show()

        palette.setColor(palette.Shadow, QtGui.QColor('red'))

        self._closeBtn = XToolButton(self)
        self._closeBtn.setIcon(
            QtGui.QIcon(resources.find('img/mdiarea/close.png')))
        self._closeBtn.setPalette(palette)
        self._closeBtn.setShadowed(True)
        self._closeBtn.setShadowRadius(10)
        self._closeBtn.setFixedSize(QtCore.QSize(22, 22))
        self._closeBtn.show()

        # create connections
        self._sysmenuBtn.clicked.connect(self.showSystemMenu)
        self._minimizeBtn.clicked.connect(self.toggleMinimized)
        self._maximizeBtn.clicked.connect(self.toggleMaximized)
        self._closeBtn.clicked.connect(self.close)
Пример #12
0
    def __init__(self, scaffold, parent=None):
        super(XScaffoldPropertiesPage, self).__init__(parent)

        # setup the scaffolding options
        self._scaffold = scaffold

        self.setTitle('Properties')
        self.setSubTitle('Setup scaffold properties')

        if scaffold.uifile():
            projexui.loadUi(__file__, self, scaffold.uifile())
        else:
            layout = QtGui.QFormLayout()

            for prop in scaffold.properties():
                # define the text
                text = prop.label
                if prop.required:
                    text += '*'
                text += ':'

                # create a checkbox
                if prop.type == 'bool':
                    widget = QtGui.QCheckBox(self)
                    widget.setProperty('propertyName', wrapVariant(prop.name))
                    widget.setText(text.strip(':'))
                    layout.addRow(None, widget)

                # create a float
                elif prop.type == 'int':
                    lbl = QtGui.QLabel(text, self)
                    widget = QtGui.QSpinBox(self)
                    widget.setProperty('propertyName', wrapVariant(prop.name))
                    layout.addRow(lbl, widget)

                # create a double
                elif prop.type == 'float':
                    lbl = QtGui.QLabel(text, self)
                    widget = QtGui.QDoubleSpinBox(self)
                    widget.setProperty('propertyName', wrapVariant(prop.name))
                    layout.addRow(lbl, widget)

                # create a text edit
                elif prop.type == 'text':
                    lbl = QtGui.QLabel(text, self)
                    widget = XTextEdit(self)
                    widget.setProperty('propertyName', wrapVariant(prop.name))
                    layout.addRow(lbl, widget)

                # create a filepath
                elif prop.type == 'file':
                    lbl = QtGui.QLabel(text, self)
                    widget = XFilepathEdit(self)

                # create an icon
                elif prop.type == 'icon':
                    widget = XIconButton(self)
                    layout.addRow(lbl, widget)

                # create a line edit
                else:
                    lbl = QtGui.QLabel(text, self)

                    if prop.choices:
                        widget = XComboBox(self)
                        widget.setProperty('dataType', 'string')
                        widget.addItems([''] + prop.choices)
                    else:
                        widget = XLineEdit(self)

                        if prop.regex:
                            regexp = QtCore.QRegExp(prop.regex)
                            validator = QtGui.QRegExpValidator(regexp, widget)
                            widget.setValidator(validator)

                    widget.setProperty('propertyName', wrapVariant(prop.name))
                    layout.addRow(lbl, widget)

            self.setLayout(layout)

        for prop, widget in self.propertyWidgetMap().items():
            if prop.default is not None:
                try:
                    widget.setHint(prop.default)
                except AttributeError:
                    projexui.setWidgetValue(widget, prop.default)
Пример #13
0
class XProgressFeedbackWidget(QtGui.QWidget):
    """ """
    def __init__(self, parent=None):
        super(XProgressFeedbackWidget, self).__init__(parent)

        # load the user interface
        projexui.loadUi(__file__, self)

        # update the ui
        self._showSecondary = False

        self.uiLoggerEDIT.hide()
        self.setProgress(0)
        self.setSecondaryProgress(0)
        self.setShowSecondaryProgress(False)

    def progress(self):
        """
        Returns the progress value for this widget.
        
        :return     <int>
        """
        return self.uiProgressBAR.value()

    def reset(self):
        """
        Resets this widget before continuing.  This is also acheived by
        setting the progress to 0.
        """
        self.setProgress(0)

    def secondaryProgress(self):
        """
        Returns the secondary progress value for this widget.
        
        :return     <int>
        """
        return self.uiSecondaryProgressBAR.value()

    def setProgress(self, value):
        """
        Sets the progress value for this widget to the inputed value.
        
        :param      value | <int>
        """
        if value == 0:
            self.uiFeedbackLBL.setText('')
            self.uiLoggerEDIT.clear()

        self.uiProgressBAR.setValue(value)

    def setSecondaryProgress(self, value):
        """
        Sets the progress value for the secondary progress widget.
        
        :param      value | <int>
        """
        self.uiSecondaryProgressBAR.setValue(value)

    def setShowSecondaryProgress(self, state):
        """
        Sets whether or not to display the secondary progress widget.
        
        :param      state | <bool>
        """
        self._showSecondary = state
        self.uiSecondaryProgressBAR.setVisible(state)

    def showEvent(self, event):
        super(XProgressFeedbackWidget, self).showEvent(event)

        self.uiSecondaryProgressBAR.setVisible(self._showSecondary)

    def showMessage(self, level, message):
        """
        Logs the inputed message for the given level.  This will update
        both the feedback label and the details widget.
        
        :param      level   | <int>
                    message | <str>
        """
        self.uiFeedbackLBL.setText(message)
        self.uiLoggerEDIT.log(level, message)

    def showSecondaryProgress(self):
        """
        Sets whether or not to display the secondary progress widget.
        
        :param      state | <bool>
        """
        return self._showSecondary

    x_showSecondaryProgress = QtCore.Property(bool, showSecondaryProgress,
                                              setShowSecondaryProgress)
Пример #14
0
    
    if dataType == 'string':
        return combo.setCurrentIndex(combo.findText(value))
    elif dataType == 'data':
        for i in range(combo.count()):
            if unwrapVariant(combo.itemData(i)) == value:
                return combo.setCurrentIndex(i)
        return combo.setCurrentIndex(-1)
    return combo.setCurrentIndex(value)

#------------------------------------------------------------------------------

# register getter/setter widget types
registerWidgetValue(QtGui.QDateEdit,
                lambda w: w.date().toPyDate(),
                lambda w, v: w.setDate(QtCore.QDate(v)))

registerWidgetValue(QtGui.QTimeEdit,
                lambda w: w.time().toPyTime(),
                lambda w, v: w.setTime(QtCore.QTime(v)))

registerWidgetValue(QtGui.QDateTimeEdit,
                lambda w: w.dateTime().toPyDateTime(),
                lambda w, v: w.setDateTime(QtCore.QDateTime(v)))

registerWidgetValue(QtGui.QGroupBox,
                lambda w: w.isChecked(),
                lambda w, v: w.setChecked(bool(v)))

registerWidgetValue(QtGui.QLineEdit,
                lambda w: nativestring(w.text()),