def __lt__(self, other):
     # make sure we're comparing apples to apples
     if not isinstance(other, QtGui.QTreeWidgetItem):
         return 0
         
     tree = self.treeWidget()
     if not tree:
         return 0
     
     col = tree.sortColumn()
     
     # compare sorting data
     mdata = unwrapVariant(self.data(col, self.SortRole))
     odata = unwrapVariant(other.data(col, self.SortRole))
     
     # compare editing data
     if mdata is None or odata is None:
         mdata = unwrapVariant(self.data(col, QtCore.Qt.EditRole))
         odata = unwrapVariant(other.data(col, QtCore.Qt.EditRole))
     
     if type(mdata) == type(odata) and not type(mdata) in (str, unicode):
         return mdata < odata
     
     # compare display data by natural sorting mechanisms on a string
     mdata = nativestring(self.text(col))
     odata = nativestring(other.text(col))
     
     return projex.sorting.natural(mdata, odata) == -1
 def setEditorData( self, editor, value ):
     """
     Sets the value for the given editor to the inputed value.
     
     :param      editor | <QWidget>
                 value  | <variant>
     """
     
     # set the data for a multitagedit
     if ( isinstance(editor, XMultiTagEdit) ):
         if ( not isinstance(value, list) ):
             value = [nativestring(value)]
         else:
             value = map(nativestring, value)
         
         editor.setTags(value)
         editor.setCurrentItem(editor.createItem())
         
     # set the data for a combobox
     elif ( isinstance(editor, QComboBox) ):
         i = editor.findText(nativestring(value))
         editor.setCurrentIndex(i)
         editor.lineEdit().selectAll()
     
     # set the data for a line edit
     elif ( isinstance(editor, QLineEdit) ):
         editor.setText(nativestring(value))
         editor.selectAll()
Beispiel #3
0
 def exportTree(self, tree, filename):
     """
     Exports the inputed tree object to the given excel file.
     
     :param      tree     | <QTreeWidget>
                 filename | <str>
     
     :return     <bool>
     """
     book = xlwt.Workbook()
     
     # determine the title for the sheet to export
     title = nativestring(tree.windowTitle())
     if not title:
         title = nativestring(tree.objectName())
     if not title:
         title = 'Sheet 1'
     
     sheet = book.add_sheet(title)
     
     # determine visible columns to export
     cols = [c for c in range(tree.columnCount()) \
             if not tree.isColumnHidden(c)]
     
     # export the column headers
     hitem = tree.headerItem()
     for c, col in enumerate(cols):
         sheet.write(0, c, nativestring(hitem.text(col)))
     
     self._currrow = 1
     for i in range(tree.topLevelItemCount()):
         self.exportTreeItem(sheet, cols, tree.topLevelItem(i))
     
     book.save(filename)
     return True
Beispiel #4
0
 def push(self, url, title=''):
     """
     Pushes the url into the history stack at the current index.
     
     :param      url | <str>
     
     :return     <bool> | changed
     """
     # ignore refreshes of the top level
     if self.currentUrl() == url or self._blockStack:
         return False
     
     self._blockStack = True
     
     self._stack = self._stack[:self._index+1]
     self._stack.append((nativestring(url), nativestring(title)))
     
     over = len(self._stack) - self.maximum()
     if over > 0:
         self._stack = self._stack[over:]
     
     self._index = len(self._stack) - 1
     
     self.canGoBackChanged.emit(self.canGoBack())
     self.canGoForwardChanged.emit(self.canGoForward())
     
     self._blockStack = False
     return True
 def recordSet( self ):
     """
     Returns the record set that is associated with this widget.
     
     :return     <orb.RecordSet> || None
     """
     if ( not self.table() ):
         return None
     
     recordSet = RecordSet(self.table())
     recordSet.setQuery(self.query())
     
     # set the grouping options
     grouping = nativestring(self.uiGroupingTXT.text()).split(',')
     while ( '' in grouping ):
         grouping.remove('')
     
     recordSet.setGroupBy( grouping )
     
     # set the sorting options
     sorting = nativestring(self.uiSortingTXT.text()).split(',')
     while ( '' in sorting ):
         sorting.remove('')
     
     recordSet.setOrder([i.split('|') for i in sorting])
     
     # set the paged options
     recordSet.setPaged(self.uiPagedCHK.isChecked())
     recordSet.setPageSize(self.uiPagedSPN.value())
     
     return recordSet
Beispiel #6
0
 def titleForFilepath( url ):
     """
     Returns a gui title for this url.
     
     :return     <str>
     """
     url = nativestring(url)
     if url in XdkEntryItem.TITLE_MAP:
         return XdkEntryItem.TITLE_MAP.get(url)
     
     url      = nativestring(url).replace('\\', '/')
     basename = os.path.basename(url)
     title    = os.path.splitext(basename)[0]
     
     if title == 'index':
         title = url.split('/')[-2]
     
     if title.endswith('-allmembers'):
         title = 'List of All Members for %s' % title.split('-')[-2]
     elif title.endswith('-source'):
         title = 'Source Code for %s' % title.split('-')[-2]
     elif len(nativestring(url).split('/')) <= 2 and title in TITLE_MAP:
         title = TITLE_MAP[title]
     elif not 'api/' in url:
         title = projex.text.pretty(title)
     
     return title
Beispiel #7
0
 def importProfile(self, filename=''):
     """
     Exports the current profile to a file.
     
     :param      filename | <str>
     """
     if not (filename and isinstance(filename, basestring)):
         filename = QtGui.QFileDialog.getOpenFileName(self,
                                                      'Import Layout from...',
                                                      QtCore.QDir.currentPath(),
                                                      'XView (*.xview)')
         
         if type(filename) == tuple:
             filename = nativestring(filename[0])
     
     filename = nativestring(filename)
     if not filename:
         return
     
     if not filename.endswith('.xview'):
         filename += '.xview'
     
     profile = XViewProfile.load(filename)
     if not profile:
         return
         
     profile.restore(self)
Beispiel #8
0
 def calculateRange(self, values):
     """
     Calculates the range of values for this axis based on the dataset
     value amount.
     
     :param      values | [<variant>, ..]
     """
     vals = filter(lambda x: x is not None, values)
     
     try:
         min_val = min(min(vals), 0)
     except ValueError:
         min_val = 0
     
     try:
         max_val = max(max(vals), 0)
     except ValueError:
         max_val = 10
     
     ndigits  = max(len(nativestring(abs(int(min_val)))), len(nativestring(abs(int(max_val)))))
     rounding = 10 ** (ndigits - 1)
     
     self.setRoundTo(rounding)
     self.setMinimum(self.rounded(min_val, rounding))
     self.setMaximum(self.rounded(max_val, rounding))
     self.reset()
Beispiel #9
0
 def setFilterData(self, key, value):
     """
     Sets the filtering information for the given key to the inputed value.
     
     :param      key | <str>
                 value | <str>
     """
     self._filterData[nativestring(key)] = nativestring(value)
 def keyColor( self, key ):
     """
     Returns a color for the inputed key (used in pie charts).
     
     :param      key | <str>
     
     :return     <QColor>
     """
     self._keyColors.setdefault(nativestring(key), self.color())
     return self._keyColors[nativestring(key)]
Beispiel #11
0
 def save(self):
     """
     Saves the state for this item to the scaffold.
     """
     enabled = self.checkState(0) == QtCore.Qt.Checked
     self._element.set('name', nativestring(self.text(0)))
     self._element.set('enabled', nativestring(enabled))
     
     for child in self.children():
         child.save()
Beispiel #12
0
 def storeValue(self, xelem, value):
     """
     Stores the value for the inptued instance to the given xml element.
     
     :param      xelem | <xml.etree.Element>
                 value | <variant>
     """
     typ = type(value)
     
     if typ == QtGui.QColor:
         xelem.set('type', 'color')
         xelem.text = nativestring(value.name())
     
     elif typ == QtCore.QPoint:
         xelem.set('type', 'point')
         xelem.text = '{0},{1}'.format(value.x(), value.y())
     
     elif typ == QtCore.QPointF:
         xelem.set('type', 'pointf')
         xelem.text = '{0},{1}'.format(value.x(), value.y())
     
     elif typ == QtCore.QRect:
         xelem.set('type', 'rect')
         xelem.text = '{0},{1},{2},{3}'.format(value.x(),
                                               value.y(),
                                               value.width(),
                                               value.height())
     
     elif typ == QtCore.QRectF:
         xelem.set('type', 'rectf')
         xelem.text = '{0},{1},{2},{3}'.format(value.x(),
                                               value.y(),
                                               value.width(),
                                               value.height())
     
     elif typ == QtCore.QByteArray:
         xelem.set('type', 'bytea')
         xelem.text = cPickle.dumps(nativestring(value))
     
     elif typ == ElementTree.Element:
         xelem.set('type', 'xml')
         xelem.append(value)
     
     elif typ in (list, tuple, dict):
         xelem.set('type', 'pickle')
         xelem.text = cPickle.dumps(value)
     
     else:
         if not typ in (str, unicode):
             value_text = nativestring(value)
         else:
             value_text = value
         
         xelem.set('type', typ.__name__)
         xelem.text = value_text
Beispiel #13
0
 def __init__(self, xdk_filename):
     # create the new XdkItem
     super(XdkItem, self).__init__(None, xdk_filename)
     
     # creates the new XdkItem
     basename = os.path.basename(nativestring(xdk_filename))
     name     = os.path.splitext(basename)[0]
     
     temppath  = nativestring(QDir.tempPath())
     temp_path = os.path.join(temppath, 'xdk/%s' % name)
     
     # define custom properties
     self._tempFilepath  = temp_path
     self._searchurls    = {}
     
     # set the options
     self.setChildIndicatorPolicy(self.ShowIndicator)
     self.setIcon(0, QIcon(projexui.resources.find('img/sdk.png')))
     
     toc_file = os.path.join(temp_path, 'toc.xml')
     toc_xml = None
     if toc_file:
         try:
             toc_xml = ElementTree.parse(toc_file).getroot()[0]
         except:
             pass
     
     if toc_xml is not None:
         self._url = 'file:///%s/index.html' % temp_path.strip('/')
         self.setText(0, toc_xml.get('title', self.text(0)))
         self.loadFromXml(toc_xml, temp_path)
     else:
         # load the url information for this entry
         for name in sorted(os.listdir(temp_path)):
             # ignore 'hidden' folders
             if name.startswith('_') and not name.startswith('__'):
                 continue
             
             # ignore special cases (only want modules for this)
             if '-' in name or name == 'toc.xml':
                 continue
             
             # use the index or __init__ information
             if name == '__init__.html':
                 self._url = 'file:///%s/%s' % (temp_path, name)
                 continue
             
             elif name == 'index.html':
                 self._url = 'file:///%s/%s' % (temp_path, name)
             
             # otherwise, load a childitem
             filepath = os.path.join(temp_path, name)
             folder = os.path.isdir(filepath)
             XdkEntryItem(self, filepath, folder=folder)
Beispiel #14
0
 def setHint(self, hint):
     """
     Sets the hint for this filepath.
     
     :param      hint | <str>
     """
     if self.normalizePath():
         filepath = os.path.normpath(nativestring(hint))
     else:
         filepath = os.path.normpath(nativestring(hint)).replace('\\', '/')
         
     self._filepathEdit.setHint(hint)
 def dictionary(self):
     """
     Returns a dictionary of the key/value pairing for the items in
     this widget.
     
     :return     {<str> key: <str> value, ..}
     """
     output = {}
     for i in range(self.topLevelItemCount() - 1):
         item = self.topLevelItem(i)
         output[nativestring(item.text(1))] = nativestring(item.text(2))
     return output
Beispiel #16
0
 def setDragData(self, format, value):
     """
     Sets the drag information that is associated with this tree
     widget item for the given format.
     
     :param      format | <str>
                 value  | <variant>
     """
     if value is None:
         self._dragData.pop(nativestring(format), None)
     else:
         self._dragData[nativestring(format)] = value
 def edit( parent, template, actions = None ):
     """
     Prompts the user to edit the menu template with the given actions. \
     If no actions are supplied, then the actions from the parent will \
     be used.
     
     :param      parent   | <QWidget>
                 template | <str>
                 actions  | {<str> name: <QAction>, .. } || None
     
     :return     (<str> template, <bool> accepted)
     """
     # collect the potential actions from the widget
     if ( actions is None ):
         actions = {}
         for action in parent.actions():
             key = nativestring(action.objectName())
             if ( not key ):
                 key = nativestring(action.text()).replace('&', '')
             
             if ( key ):
                 actions[key] = action
     
     if ( not actions ):
         return ('', False)
     
     dlg = QDialog(parent)
     dlg.setWindowTitle('Edit Menu')
     
     widget = XMenuTemplateWidget(dlg)
     widget.setActions(actions)
     widget.setMenuTemplate(template)
     widget.layout().setContentsMargins(0, 0, 0, 0)
     
     opts = QDialogButtonBox.Save | QDialogButtonBox.Cancel
     btns = QDialogButtonBox(opts, Qt.Horizontal, dlg)
     
     btns.accepted.connect( dlg.accept )
     btns.rejected.connect( dlg.reject )
     
     layout = QVBoxLayout()
     layout.addWidget(widget)
     layout.addWidget(btns)
     
     dlg.setLayout(layout)
     dlg.adjustSize()
     dlg.resize(650, 400)
     
     if ( dlg.exec_() ):
         return (widget.menuTemplate(), True)
     return ('', False)
 def showWizards( self ):
     """
     Show the wizards widget for the currently selected plugin.
     """
     self.uiWizardTABLE.clear()
     
     item = self.uiPluginTREE.currentItem()
     if ( not (item and item.parent()) ):
         plugins = []
     else:
         wlang   = nativestring(item.parent().text(0))
         wgrp    = nativestring(item.text(0))
         plugins = self.plugins(wlang, wgrp)
     
     if ( not plugins ):
         self.uiWizardTABLE.setEnabled(False)
         self.uiDescriptionTXT.setEnabled(False)
         return
     
     self.uiWizardTABLE.setEnabled(True)
     self.uiDescriptionTXT.setEnabled(True)
     
     # determine the number of columns
     colcount = len(plugins) / 2
     if ( len(plugins) % 2 ):
         colcount += 1
     
     self.uiWizardTABLE.setRowCount(2)
     self.uiWizardTABLE.setColumnCount( colcount )
     
     header = self.uiWizardTABLE.verticalHeader()
     header.setResizeMode(0, header.Stretch)
     header.setResizeMode(1, header.Stretch)
     header.setMinimumSectionSize(64)
     header.hide()
     
     header = self.uiWizardTABLE.horizontalHeader()
     header.setMinimumSectionSize(64)
     header.hide()
     
     col = -1
     row = 1
     for plugin in plugins:
         if ( row ):
             col += 1
         
         row     = int(not row)
         widget  = PluginWidget(self, plugin)
         
         self.uiWizardTABLE.setItem(row, col, QTableWidgetItem())
         self.uiWizardTABLE.setCellWidget(row, col, widget)
Beispiel #19
0
 def handleButtonClick( self, button ):
     """
     Handle the event when a user clicks on one of the part buttons.
     
     :param      button | <QToolButton>
     """
     path            = button.property('path')
     is_completer    = button.property('is_completer')
     
     # popup a completion menu
     if ( unwrapVariant(is_completer) ):
         model = self.navigationModel()
         if ( not model ):
             return
         
         sep  = self.separator()
         path = nativestring(unwrapVariant(path))
         item = model.itemByPath(path, includeRoot = True)
         if ( not item ):
             return
         
         curr_path = nativestring(self.text()).strip(self.separator())
         curr_path = curr_path.replace(path, '').strip(self.separator())
         
         child_name = ''
         if ( curr_path ):
             child_name = curr_path.split(self.separator())[0]
         
         index = model.indexFromItem(item)
         
         self._completerTree.move(QCursor.pos())
         self._completerTree.setRootIndex(index)
         self._completerTree.verticalScrollBar().setValue(0)
         
         if ( child_name ):
             child_item = None
             for i in range(item.rowCount()):
                 child = item.child(i)
                 if ( child.text() == child_name ):
                     child_item = child
                     break
             
             if ( child_item ):
                 child_index = model.indexFromItem(child_item)
                 self._completerTree.setCurrentIndex(child_index)
                 self._completerTree.scrollTo(child_index)
         
         self._completerTree.show()
         self._completerTree.setUpdatesEnabled(True)
     else:
         self.setText(unwrapVariant(path))
Beispiel #20
0
 def columns( self ):
     """
     Returns the list of column names for this table widget's columns.
     
     :return     [<str>, ..]
     """
     output = []
     for c in range(self.columnCount()):
         hitem  = self.horizontalHeaderItem(c)
         text = nativestring(hitem.text())
         if ( not text ):
             text = nativestring(hitem.toolTip())
         output.append(text)
     return output
Beispiel #21
0
 def dispatch(location='Central'):
     """
     Returns the instance of the global view dispatching system.  All views \
     will route their signals through the central hub so no single view \
     necessarily depends on another.
     
     :return     <XViewDispatch>
     """
     dispatch = XView._dispatch.get(nativestring(location))
     if not dispatch:
         dispatch = XViewDispatch(QApplication.instance())
         XView._dispatch[nativestring(location)] = dispatch
     
     return dispatch
Beispiel #22
0
 def filterItems(self, 
                 terms, 
                 caseSensitive=False):
     """
     Filters the items in this tree based on the inputed text.
     
     :param      terms           | <str> || {<str> datatype: [<str> opt, ..]}
                 caseSensitive   | <bool>
     """
     # create a dictionary of options
     if type(terms) != dict:
         terms = {'*': nativestring(terms)}
     
     # validate the "all search"
     if '*' in terms and type(terms['*']) != list:
         sterms = nativestring(terms['*'])
         
         if not sterms.strip():
             terms.pop('*')
         else:
             dtype_matches = DATATYPE_FILTER_EXPR.findall(sterms)
             
             # generate the filter for each data type
             for match, dtype, values in dtype_matches:
                 sterms = sterms.replace(match, '')
                 terms.setdefault(dtype, [])
                 terms[dtype] += values.split(',')
             
             keywords = sterms.replace(',', '').split()
             while '' in keywords:
                 keywords.remove('')
             
             terms['*'] = keywords
     
     # filter out any data types that are not being searched
     filtered_dtypes = self.filteredDataTypes()
     filter_terms = {}
     for dtype, keywords in terms.items():
         if dtype != '*' and not dtype in filtered_dtypes:
             continue
         
         if not caseSensitive:
             keywords = [nativestring(keyword).lower() for keyword in keywords]
         else:
             keywords = map(nativestring, keywords)
         
         filter_terms[dtype] = keywords
     
     self.__filterItems(filter_terms, caseSensitive)
Beispiel #23
0
 def pickAttachment(self):
     """
     Prompts the user to select an attachment to add to this edit.
     """
     filename = QFileDialog.getOpenFileName(self.window(),
                                            'Select Attachment',
                                            '',
                                            'All Files (*.*)')
     
     if type(filename) == tuple:
         filename = nativestring(filename[0])
     
     filename = nativestring(filename)
     if filename:
         self.addAttachment(os.path.basename(filename), filename)
Beispiel #24
0
 def value( self ):
     """
     Returns the current value of the current pair's value.
     
     :return     <str>
     """
     return nativestring(self._valueEdit.text())
Beispiel #25
0
 def title( self ):
     """
     Returns the title for this rollout.
     
     :return     <str>
     """
     return nativestring(self._titleLabel.text())
 def drawDisplay(self, painter, option, rect, text):
     """
     Overloads the drawDisplay method to render HTML if the rich text \
     information is set to true.
     
     :param      painter | <QtGui.QPainter>
                 option  | <QtGui.QStyleOptionItem>
                 rect    | <QtCore.QRect>
                 text    | <str>
     """
     if self.showRichText():
         # create the document
         doc = QtGui.QTextDocument()
         doc.setTextWidth(float(rect.width()))
         doc.setHtml(text)
         
         # draw the contents
         painter.translate(rect.x(), rect.y())
         doc.drawContents(painter, QtCore.QRectF(0, 
                                                 0, 
                                                 float(rect.width()), 
                                                 float(rect.height())))
                                          
         painter.translate(-rect.x(), -rect.y())
     else:
         if type(text).__name__ not in ('str', 'unicode', 'QString'):
             text = nativestring(text)
         
         metrics = QtGui.QFontMetrics(option.font)
         text = metrics.elidedText(text,
                                   QtCore.Qt.TextElideMode(option.textElideMode),
                                   rect.width())
         
         painter.setFont(option.font)
         painter.drawText(rect, int(option.displayAlignment), text)
 def setDateFormat(self, format):
     """
     Sets the date format for this delegate.
     
     :param      format | <str>
     """
     self._dateFormat = nativestring(format)
Beispiel #28
0
 def key( self ):
     """
     Returns the current value of the current pair's key.
     
     :return     <str>
     """
     return nativestring(self._keyEdit.text())
 def addEntry(self, key='', value=''):
     """
     Creates a new entry item for this widget.
     
     :param      key     | <str>
                 value   | <variant>
     """
     img = resources.find('img/close.png')
     new_item = XTreeWidgetItem()
     new_item.setText(1, nativestring(key))
     new_item.setText(2, nativestring(value))
     new_item.setIcon(0, QtGui.QIcon(img))
     new_item.setFixedHeight(22)
     self.insertTopLevelItem(self.topLevelItemCount() - 1, new_item)
     
     return new_item
Beispiel #30
0
 def setValue( self, value ):
     # ignore password values since they are encrypted and we don't want
     # to encrypt them multiple times
     if ( value ):
         value = IGNORED
     
     self.setText(nativestring(value))
Beispiel #31
0
 def setDragData(self, key, value):
     """
     Sets the drag data associated with this data set.  This will be 
     used when the user attempts to drag & drop a data set from the
     chart somewhere.  If no key is supplied, then the full data dictionary
     is returned.  The drag data key will be joined as:
     
         application/x-[key]
     
     :param      key     | <str> || None
                 value   | <variant>
     """
     self._dragData[nativestring(key)] = value
Beispiel #32
0
    def itemPath(self, item):
        """
        Returns the path for the inputed item based on its hierarchy.
        
        :return     <str>
        """
        path = []
        while (item):
            path.insert(0, nativestring(item.text()))
            item = item.parent()

        sep = self.separator()
        return sep + sep.join(path)
Beispiel #33
0
 def filterData(self, key):
     """
     Returns the filter data for the given key.
     
     :param      key | <str>
     
     :return     <str>
     """
     if key == 'text':
         default = nativestring(self.text())
     else:
         default = ''
     return self._filterData.get(key, default)
Beispiel #34
0
 def setText(self, text):
     """
     Sets the text for this button.  If it is set to show rich text, then
     it will update the label text, leaving the root button text blank, 
     otherwise it will update the button.
     
     :param      text | <str>
     """
     self._text = nativestring(text)
     if self.showRichText():
         self.richTextLabel().setText(text)
     else:
         super(XPushButton, self).setText(text)
Beispiel #35
0
 def setFilepathModeText( self, text ):
     """
     Sets the filepath mode for this widget based on the inputed text.
     
     :param      text | <str>
     
     :return     <bool> | success
     """
     try:
         self.setFilepathMode(XFilepathEdit.Mode[nativestring(text)])
         return True
     except KeyError:
         return False
Beispiel #36
0
    def formatValue(self, value):
        """
        Formats the inputed value based on the formatting system for this ruler.
        
        :param      value | <variant>
        """
        formatter = self.formatter()
        if (formatter is not None):
            return formatter(value)

        elif (self.format()):
            rtype = self.rulerType()
            if (rtype in (XChartRuler.Type.Date, XChartRuler.Type.Datetime,
                          XChartRuler.Type.Time)):
                return value.toString(self.format())
            else:
                try:
                    return self.format() % value
                except TypeError:
                    return nativestring(value)

        return nativestring(value)
Beispiel #37
0
 def pickFilepath( self ):
     """
     Picks the image file to use for this icon path.
     """
     filepath = QFileDialog.getOpenFileName( self,
                                             'Select Image File',
                                             QDir.currentPath(),
                                             self.fileTypes())
     
     if type(filepath) == tuple:
         filepath = nativestring(filepath[0])
     
     if ( filepath ):
         self.setFilepath(filepath)
    def currentSchemaPath(self):
        """
        Returns the column path for the current item.  This will be a '.'
        joined path based on the root schema to the given column.
        
        :return     <str>
        """
        item = self.currentItem()
        path = []
        while item:
            path.append(nativestring(item.text(0)))
            item = item.parent()

        return '.'.join(reversed(path))
    def buildData(self, key=None, default=None):
        """
        Returns the build information for this item for the given key, 
        or all build information if the supplied key is None.
        
        :param      key     | <str> || None
                    default | <variant>
        
        :return     <variant>
        """
        if key is None:
            return self._buildData

        return self._buildData.get(nativestring(key), default)
Beispiel #40
0
    def removeAttachment(self, title):
        """
        Removes the attachment from the given title.
        
        :param      title | <str>
        
        :return     <variant> | attachment
        """
        attachment = self._attachments.pop(nativestring(title), None)

        if attachment:
            self.resizeToContents()

        return attachment
Beispiel #41
0
    def removeAxis(self, axis):
        """
        Removes an axis from this chart either by direct reference or by
        name.
        
        :param      axis | <projexui.widgets.XChartAxis> || <str>
        """
        if not isinstance(axis, XChartAxis):
            axis = self.axis(nativestring(axis))

        try:
            self._axes.remove(axis)
        except ValueError:
            pass
Beispiel #42
0
 def isValid( self ):
     """
     Returns whether or not the filepath exists on the system. \
     In the case of a SaveFile, only the base folder \
     needs to exist on the system, in other modes the actual filepath must \
     exist.
     
     :return     <bool>
     """
     check = nativestring(self._filepathEdit.text()).split(os.path.pathsep)[0]
     if ( self.filepathMode() == XFilepathEdit.Mode.SaveFile ):
         check = os.path.dirname(check)
     
     return os.path.exists(check)
Beispiel #43
0
    def record(viewWidget):
        """
        Records the state for the inputed view widget into data.
        
        :param      viewWidget | <XViewWidget>
        """
        profile = XViewProfile()

        xprofile = ElementTree.Element('profile')
        xprofile.set('locked', nativestring(viewWidget.isLocked()))
        XViewProfile.recordWidget(xprofile, viewWidget.widget())
        profile.setXmlElement(xprofile)

        return profile
Beispiel #44
0
    def fileName(self):
        """
        Returns the filename.
        
        :return     <str>
        """
        if self._filename:
            return self._filename

        filename = nativestring(super(XSettings, self).fileName())
        if self._customFormat:
            filename, ext = os.path.splitext(filename)
            filename += '.' + self._customFormat.extension()
        return filename
Beispiel #45
0
    def setText(self, text):
        """
        Sets the text for this serial edit to the inputed text.
        
        :param      text | <str>
        """
        texts = nativestring(text).split(' ')

        for i, text in enumerate(texts):
            editor = self.editorAt(i)
            if not editor:
                break

            editor.setText(text)
Beispiel #46
0
def generateResourceFile(srcpath, outpath='', buildpath='', build=True):
    """
    Generates a Qt resource file based on the given source path.  This will
    take all the files and folders within the source and generate a new XML
    representation of that path.  An optional outpath can be provided as the
    generated resource path, by default it will be called the name of the
    source path.
    
    :param      srcpath | <str>
                outpath | <str>
    """
    if not outpath:
        outpath = os.path.join(os.path.dirname(srcpath),
                               os.path.basename(srcpath) + '.qrc')
        relpath = './%s' % os.path.basename(srcpath)
    else:
        relpath = os.path.relpath(srcpath, os.path.dirname(outpath))

    xml = ElementTree.Element('RCC')
    xml.set('header', 'projexui.resources')

    srcpath = nativestring(srcpath)
    srcpath = os.path.normpath(srcpath)
    root_prefix = os.path.basename(srcpath) + '/'
    count = len(srcpath)

    for root, folders, files in os.walk(srcpath):
        if not files:
            continue

        relpath = os.path.relpath(root, os.path.dirname(outpath))
        prefix = (root_prefix + root[count + 1:].replace('\\', '/')).strip('/')

        xresource = ElementTree.SubElement(xml, 'qresource')
        xresource.set('prefix', prefix)

        for file in files:
            xfile = ElementTree.SubElement(xresource, 'file')
            xfile.set('alias', file)
            xfile.text = os.path.join(relpath, file).replace('\\', '/')

    projex.text.xmlindent(xml)
    xml_str = ElementTree.tostring(xml)

    # save the exported information
    with open(outpath, 'w') as f:
        f.write(xml_str)

    if build:
        buildResourceFile(outpath, buildpath)
Beispiel #47
0
    def dragMoveEvent(self, event):
        """
        Handles the drag move event.
        
        :param      event | <QDragEvent>
        """
        tags = nativestring(event.mimeData().text())

        if (event.source() == self):
            event.acceptProposedAction()
        elif (tags):
            event.acceptProposedAction()
        else:
            super(XMultiTagEdit, self).dragMoveEvent(event)
Beispiel #48
0
    def setHint(self, text):
        """
        Sets the hint to the inputed text.   The same hint will be used for
        all editors in this widget.
        
        :param      text | <str>
        """
        texts = nativestring(text).split(' ')

        for i, text in enumerate(texts):
            editor = self.editorAt(i)
            if not editor:
                break

            editor.setHint(text)
 def plugins( self, typ = None, group = None ):
     """
     Returns the plugins used for this dialog.
     
     :param      typ      | <str> || None
                 group    | <str> || None
     
     :return     [<XWizardPlugin>, ..]
     """
     if ( typ is None ):
         output = []
         for wlang in self._plugins.values():
             for wgrp in wlang.values():
                 output += wgrp
         return output
         
     elif ( group is None ):
         output = []
         for wgrp in self._plugins.get(nativestring(typ), {}).values():
             output += wgrp
         return output
     
     else:
         return self._plugins.get(nativestring(typ), {}).get(nativestring(group), [])
Beispiel #50
0
 def setColumnTypeText( self, columnTypeText ):
     """
     Sets the column type for this widget based on the inputed text.
     
     :param      columnTypeText | <str>
     """
     if ( not ColumnType ):
         return False
     
     try:
         columnType = ColumnType[nativestring(columnTypeText)]
     except KeyError:
         return False
     
     return self.setColumnType(columnType)
Beispiel #51
0
    def setColor(self, key, value):
        """
        Sets the color value for the inputed color.
        
        :param      key     | <unicode>
                    value   | <QtGui.QColor>
        """
        key = nativestring(key).capitalize()
        self._colorSet.setColor(key, value)

        # update the palette information
        if (key == 'Background'):
            palette = self.palette()
            palette.setColor(palette.Base, value)
            self.setPalette(palette)
Beispiel #52
0
    def currentRecord(self):
        """
        Returns the current record based on the active index from the model.
        
        :return     <orb.Table> || None
        """
        completion = nativestring(self._pywidget.text())
        options = map(str, self.model().stringList())

        try:
            index = options.index(completion)
        except ValueError:
            return None

        return self._records[index]
Beispiel #53
0
 def saveValues(self):
     """
     Generates a dictionary of values from the widgets in this editor that
     will be used to save the values on its record.
     
     :return     {<str> columnName: <variant> value, ..}
     """
     output = {}
     
     for widget in self.findChildren(QWidget):
         prop = widget.property('columnName')
         if not prop:
             continue
         
         columnName = nativestring(unwrapVariant(prop, ''))
         
         if ( not columnName ):
             continue
         
         value, success = projexui.widgetValue(widget)
         if ( not success ):
             continue
         
         # convert from values to standard python values
         if ( isinstance(value, QDateTime) ):
             value = value.toPyDateTime()
         elif ( isinstance(value, QDate) ):
             value = value.toPyDate()
         elif ( isinstance(value, QTime) ):
             value = value.toPyTime()
         elif ( type(value).__name__ == 'QString' ):
             value = nativestring(value)
         
         output[columnName] = value
     
     return output
Beispiel #54
0
    def mimeData(self, items):
        """
        Creates the mime data for the different items.
        
        :param      items | [<QListWidgetItem>, ..]
        
        :return     <QMimeData>
        """
        text = []
        for item in items:
            text.append(nativestring(item.text()))

        data = QMimeData()
        data.setText(','.join(text))
        return data
Beispiel #55
0
    def splitPath(self, path):
        """
        Splits the path into its components.
        
        :param      path | <str>
        
        :return     [<str>, ..]
        """
        sep = self.model().separator()
        splt = nativestring(path).lstrip(sep).split(sep)

        if (splt and not splt[-1]):
            self.model().itemByPath(path)

        return splt
Beispiel #56
0
 def pathFromIndex(self, index):
     """
     Returns the joined path from the given model index.  This will
     join together the full path with periods.
     
     :param      index | <QModelIndex>
     
     :return     <str>
     """
     out  = []
     while index and index.isValid():
         out.append(nativestring(unwrapVariant(index.data())))
         index = self._model.parent(index)
     
     return self.joiner().join(reversed(out))
Beispiel #57
0
 def editorValue(self, editor):
     """
     Returns the value for this plugin from the inputed editor.
     
     :param      editor | <QtGui.QWidget>
     
     :return     <variant>
     """
     if isinstance(editor, QLineEdit):
         try:
             return eval(nativestring(editor.text()))
         except:
             return 0
     else:
         return super(NumericPlugin, self).editorValue(editor)
Beispiel #58
0
    def load(self, filename, lineno=0):
        """
        Loads the inputed filename as the current document for this edit.
        
        :param      filename | <str>
                    lineno   | <int>
        
        :return     <bool> | success
        """
        filename = nativestring(filename)

        if (not (filename and os.path.exists(filename))):
            return False

        # load the file
        docfile = QFile(filename)
        if (not docfile.open(QFile.ReadOnly)):
            return False

        success = self.read(docfile)
        docfile.close()

        if (not success):
            return False

        self._filename = nativestring(filename)
        ext = os.path.splitext(filename)[1]
        self.setCurrentLine(lineno)

        lang = XLanguage.byFileType(ext)
        if (lang != self.language()):
            self.setLanguage(lang)

        self.setModified(False)

        return True
Beispiel #59
0
def findUiActions(widget):
    """
    Looks up actions for the inputed widget based on naming convention.
    
    :param      widget | <QWidget>
    
    :return     [<QAction>, ..]
    """
    import_qt(globals())

    output = []
    for action in widget.findChildren(QtGui.QAction):
        name = nativestring(action.objectName()).lower()
        if (name.startswith('ui') and name.endswith('act')):
            output.append(action)
    return output
Beispiel #60
0
    def validatePage(self):
        """
        Finishes up the structure information for this wizard by building
        the scaffold.
        """
        path = self.uiOutputPATH.filepath()

        for item in self.uiStructureTREE.topLevelItems():
            item.save()

        try:
            self.scaffold().build(path, self._structure)
        except Exception, err:
            QtGui.QMessageBox.critical(None, 'Error Occurred',
                                       nativestring(err))
            return False