def __init__(self, name, **options): # define custom properties self._name = name self._chart = None self._orientation = options.get('orientation', Qt.Horizontal) self._showLabels = options.get('showLabels', True) self._shadeAxis = options.get('shadeAxis', None) self._minimum = options.get('minimum', None) self._maximum = options.get('maximum', None) self._values = options.get('values', None) self._labels = options.get('labels', None) self._labelFont = options.get('labelFont', QApplication.font()) self._labelFormat = options.get('labelFormat', '{0}') self._hLabelPad = options.get('horizontalLabelPadding', 6) self._vLabelPad = options.get('verticalLabelPadding', 3) self._title = options.get('title', '') self._maximumLabelCount = options.get('maximumLabelCount', None) self._minimumLabelWidth = options.get('minimumLabelWidth', 32) self._minimumLabelHeight = options.get('minimumLabelHeight', 22) # setup default dynamic options self._dynamicRange = options.get('useDynamicRange', not 'labels' in options) self._dynamicScalingEnabled = options.get('dynamicScalingEnabled', False) # setup default title font titleFont = QApplication.font() titleFont.setBold(True) self._titleFont = options.get('titleFont', titleFont)
def search(self): """ Looks up the current search terms from the xdk files that are loaded. """ QApplication.instance().setOverrideCursor(Qt.WaitCursor) terms = nativestring(self.uiSearchTXT.text()) html = [] entry_html = '<a href="%(url)s">%(title)s</a><br/>'\ '<small>%(url)s</small>' for i in range(self.uiContentsTREE.topLevelItemCount()): item = self.uiContentsTREE.topLevelItem(i) results = item.search(terms) results.sort(lambda x, y: cmp(y['strength'], x['strength'])) for item in results: html.append(entry_html % item) if (not html): html.append('<b>No results were found for %s</b>' % terms) self.uiSearchWEB.setHtml(SEARCH_HTML % '<br/><br/>'.join(html)) QApplication.instance().restoreOverrideCursor()
def reset(self): """ Resets the values to the current application information. """ self.setValue('colorSet', XPaletteColorSet()) self.setValue('font', QApplication.font()) self.setValue('fontSize', QApplication.font().pointSize())
def showEvent(self, event): super(XScintillaEdit, self).showEvent(event) if self._dirty: self._dirty = False language = self.language() self.setLexer(None) # grab the language from the lang module if it is a string if language and type(language) != XLanguage: language = XLanguage.byName(language) # collect the language's lexer if not language: return if language.tabWidth(): self.setTabWidth(language.tabWidth()) lexer = language.createLexer(self, self._colorSet) if not lexer: return # update the margins font mfont = QFont(self.font()) mfont.setPointSize(mfont.pointSize() - 2) self.setMarginsFont(mfont) QApplication.sendPostedEvents(self, -1) # hack to force update the colors for i in range(100): lexer.setColor(lexer.color(i), i)
def save(self): """ Saves the snapshot based on the current region. """ # close down the snapshot widget if self.hideWindow(): self.hideWindow().hide() self.hide() QApplication.processEvents() time.sleep(1) # create the pixmap to save wid = QApplication.desktop().winId() if not self._region.isNull(): x = self._region.x() y = self._region.y() w = self._region.width() h = self._region.height() else: x = self.x() y = self.y() w = self.width() h = self.height() pixmap = QPixmap.grabWindow(wid, x, y, w, h) pixmap.save(self.filepath()) self.close() self.deleteLater() if self.hideWindow(): self.hideWindow().show()
def reset( self ): """ Resets the values to the current application information. """ self.setValue('colorSet', XPaletteColorSet()) self.setValue('font', QApplication.font()) self.setValue('fontSize', QApplication.font().pointSize())
def __init__(self, parent=None): super(XdkWindow, self).__init__(parent) # load the user interface projexui.loadUi(__file__, self) # define custom properties self._currentContentsIndex = -1 self._worker = XdkWorker() self._workerThread = QThread() self._worker.moveToThread(self._workerThread) self._workerThread.start() # set default properties self.setAcceptDrops(True) self.setAttribute(Qt.WA_DeleteOnClose) self.uiFindNextBTN.setDefaultAction(self.uiFindNextACT) self.uiFindPrevBTN.setDefaultAction(self.uiFindPrevACT) self.uiFindWIDGET.setVisible(False) self.uiSearchWEB.page().setLinkDelegationPolicy( QWebPage.DelegateAllLinks) self.refreshUi() # connect widgets self.uiContentsTAB.currentChanged.connect(self.refreshUi) self.uiContentsTAB.tabCloseRequested.connect(self.closeContentsWidget) self.uiContentsTREE.itemExpanded.connect(self.loadItem) self.uiContentsTREE.itemSelectionChanged.connect(self.refreshContents) self.uiSearchTXT.returnPressed.connect(self.search) self.uiSearchWEB.linkClicked.connect(self.gotoUrl) self.uiIndexTREE.itemSelectionChanged.connect(self.refreshFromIndex) # connect find actions self.uiBackACT.triggered.connect(self.goBack) self.uiForwardACT.triggered.connect(self.goForward) self.uiHomeACT.triggered.connect(self.goHome) self.uiFindTXT.textChanged.connect(self.findNext) self.uiFindTXT.returnPressed.connect(self.findNext) self.uiFindNextACT.triggered.connect(self.findNext) self.uiFindPrevACT.triggered.connect(self.findPrev) self.uiFindACT.triggered.connect(self.showFind) self.uiFindCloseBTN.clicked.connect(self.uiFindWIDGET.hide) self.uiCopyTextACT.triggered.connect(self.copyText) # connect zoom actions self.uiZoomResetACT.triggered.connect(self.zoomReset) self.uiZoomInACT.triggered.connect(self.zoomIn) self.uiZoomOutACT.triggered.connect(self.zoomOut) # connect file actions self.uiLoadACT.triggered.connect(self.loadFilename) self.uiNewTabACT.triggered.connect(self.addContentsWidget) self.uiCloseTabACT.triggered.connect(self.closeContentsWidget) self.uiQuitACT.triggered.connect(self.close) # connect the signals self.loadFileRequested.connect(self._worker.loadFile) self._worker.loadingFinished.connect(self._addXdkItem) QApplication.instance().aboutToQuit.connect(self._cleanupWorker)
def exec_(self, pos=None): self._result = 0 self.setWindowModality(Qt.ApplicationModal) self.popup(pos) while self.isVisible(): QApplication.processEvents() return self.result()
def copy( self ): """ Copies the selected items to the clipboard. """ text = [] for item in self.selectedItems(): text.append(nativestring(item.text())) QApplication.clipboard().setText(','.join(text))
def copy(self): """ Copies the selected items to the clipboard. """ text = [] for item in self.selectedItems(): text.append(nativestring(item.text())) QApplication.clipboard().setText(','.join(text))
def show(self): """ Shows this widget and hides the specified window if necessary. """ super(XSnapshotWidget, self).show() if self.hideWindow(): self.hideWindow().hide() QApplication.processEvents()
def instance(): if XIOHook._instance is None: XIOHook._instance = XIOHook() # create the hook registration hooks.registerStdOut(XIOHook.stdout) hooks.registerStdErr(XIOHook.stderr) QApplication.instance().aboutToQuit.connect(XIOHook.cleanup) return XIOHook._instance
def load(self): """ Loads the records from the query set linked with this item. """ if self._loaded: return rset = self.recordSet() QApplication.setOverrideCursor(Qt.WaitCursor) self.loadRecords(rset) QApplication.restoreOverrideCursor()
def setCheckedRecords( self, records ): """ Sets the checked off records to the list of inputed records. :param records | [<orb.Table>, ..] """ QApplication.sendPostedEvents(self, -1) indexes = [] for i in range(self.count()): record = self.recordAt(i) if record is not None and record in records: indexes.append(i) self.setCheckedIndexes(indexes)
def __init__(self, parent=None): # needs to be defined before the base class is initialized or the # event filter won't work self._treePopupWidget = None super(XOrbRecordBox, self).__init__( parent ) # define custom properties self._currentRecord = None # only used while loading self._changedRecord = -1 self._tableTypeName = '' self._tableLookupIndex = '' self._baseHints = ('', '') self._batchSize = 100 self._tableType = None self._order = None self._query = None self._iconMapper = None self._labelMapper = nstr self._required = True self._loaded = False self._showTreePopup = False self._autoInitialize = False self._threadEnabled = True self._specifiedColumns = None self._specifiedColumnsOnly = False # define an editing timer self._editedTimer = QTimer(self) self._editedTimer.setSingleShot(True) self._editedTimer.setInterval(500) # create threading options self._worker = None self._workerThread = None # create connections edit = self.lineEdit() if edit: edit.textEntered.connect(self.assignCurrentRecord) edit.editingFinished.connect(self.emitCurrentRecordEdited) edit.returnPressed.connect(self.emitCurrentRecordEdited) self.currentIndexChanged.connect(self.emitCurrentRecordChanged) self.currentIndexChanged.connect(self.startEditTimer) self._editedTimer.timeout.connect(self.emitCurrentRecordEdited) QApplication.instance().aboutToQuit.connect(self._cleanupWorker)
def adjustButtons(self): """ Updates the position of the buttons based on the current geometry. """ tabbar = self.tabBar() tabbar.adjustSize() w = self.width() - self._optionsButton.width() - 2 self._optionsButton.move(w, 0) if self.count(): need_update = self._addButton.property('alone') != False if need_update: self._addButton.setProperty('alone', False) self._addButton.move(tabbar.width(), 1) self._addButton.setFixedHeight(tabbar.height()) else: need_update = self._addButton.property('alone') != True if need_update: self._addButton.setProperty('alone', True) self._addButton.move(tabbar.width() + 2, 1) self._addButton.stackUnder(self.currentWidget()) # force refresh on the stylesheet (Qt limitation for updates) if need_update: app = QApplication.instance() app.setStyleSheet(app.styleSheet())
def adjustButtons( self ): """ Updates the position of the buttons based on the current geometry. """ tabbar = self.tabBar() tabbar.adjustSize() w = self.width() - self._optionsButton.width() - 2 self._optionsButton.move(w, 0) if self.count(): need_update = self._addButton.property('alone') != False if need_update: self._addButton.setProperty('alone', False) self._addButton.move(tabbar.width(), 1) self._addButton.setFixedHeight(tabbar.height()) else: need_update = self._addButton.property('alone') != True if need_update: self._addButton.setProperty('alone', True) self._addButton.move(tabbar.width() + 2, 1) self._addButton.stackUnder(self.currentWidget()) # force refresh on the stylesheet (Qt limitation for updates) if need_update: app = QApplication.instance() app.setStyleSheet(app.styleSheet())
def drawItem(self, item, painter, option): """ Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem> """ dataset = item.dataset() painter.save() painter.setRenderHint(painter.Antialiasing) pen = QPen(dataset.color()) pen.setWidth(3) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(item.path()) if self.showPoints(): palette = QApplication.palette() pen = QPen(palette.color(palette.Base)) pen.setWidth(2) painter.setBrush(dataset.color()) painter.setPen(pen) for point in item.buildData('ellipses', []): painter.drawEllipse(point, self.pointRadius(), self.pointRadius()) painter.restore()
def copyFilepath( self ): """ Copies the current filepath contents to the current clipboard. """ clipboard = QApplication.instance().clipboard() clipboard.setText(self.filepath()) clipboard.setText(self.filepath(), clipboard.Selection)
def update( self, recursive = False ): if ( not self.childCount() ): return # update the look for the group font = self.font(0) font.setBold(True) self.setFont(0, font) for i in range(self.columnCount()): self.setText(i, '') # make sure we size properly self.setSizeHint(0, QSize(150, 20)) self.setFirstColumnSpanned(True) palette = QApplication.instance().palette() if ( not self.isExpanded() ): self.setForeground(0, palette.color(palette.Mid)) else: self.setForeground(0, palette.color(palette.AlternateBase)) self.setText(0, '(%s)' % self.summary()) if ( recursive ): for c in range( self.childCount() ): self.child(c).update(True)
def showPopup(self): """ Shows the popup for this button. """ as_dialog = QApplication.keyboardModifiers() anchor = self.defaultAnchor() if anchor: self.popupWidget().setAnchor(anchor) else: anchor = self.popupWidget().anchor() if ( anchor & (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter | XPopupWidget.Anchor.BottomRight) ): pos = QPoint(self.width() / 2, 0) else: pos = QPoint(self.width() / 2, self.height()) pos = self.mapToGlobal(pos) if not self.signalsBlocked(): self.popupAboutToShow.emit() self._popupWidget.popup(pos) if as_dialog: self._popupWidget.setCurrentMode(XPopupWidget.Mode.Dialog)
def update(self, recursive=False): if (not self.childCount()): return # update the look for the group font = self.font(0) font.setBold(True) self.setFont(0, font) for i in range(self.columnCount()): self.setText(i, '') # make sure we size properly self.setSizeHint(0, QSize(150, 20)) self.setFirstColumnSpanned(True) palette = QApplication.instance().palette() if (not self.isExpanded()): self.setForeground(0, palette.color(palette.Mid)) else: self.setForeground(0, palette.color(palette.AlternateBase)) self.setText(0, '(%s)' % self.summary()) if (recursive): for c in range(self.childCount()): self.child(c).update(True)
def paste(self): """ Pastes text from the clipboard into this edit. """ html = QApplication.clipboard().text() if not self.isRichTextEditEnabled(): self.insertPlainText(projex.text.toAscii(html)) else: super(XTextEdit, self).paste()
def paste( self ): """ Pastes text from the clipboard. """ text = nativestring(QApplication.clipboard().text()) for tag in text.split(','): tag = tag.strip() if ( self.isTagValid(tag) ): self.addTag(tag)
def paste(self): """ Pastes text from the clipboard. """ text = nativestring(QApplication.clipboard().text()) for tag in text.split(','): tag = tag.strip() if (self.isTagValid(tag)): self.addTag(tag)
def __init__( self, chartWidget ): super(XChartScene, self).__init__(chartWidget) # create custom properties self._chartWidget = chartWidget self._minimumWidth = -1 self._minimumHeight = -1 self._maximumWidth = -1 self._maximumHeight = -1 self._horizontalPadding = 6 self._verticalPadding = 6 self._showGrid = True self._showRows = True self._showColumns = True self._trackingEnabled = True self._chartType = XChartScene.Type.Line self._trackerItem = None # used with pie charts self._pieAxis = Qt.YAxis self._pieAlignment = Qt.AlignCenter self._horizontalRuler = XChartRuler(XChartRuler.Type.Number) self._verticalRuler = XChartRuler(XChartRuler.Type.Number) self._font = QApplication.font() self._alternatingColumnColors = False self._alternatingRowColors = True self._dirty = False self._buildData = {} palette = QApplication.palette() self._axisColor = palette.color(palette.Mid).darker(125) self._baseColor = palette.color(palette.Base) self._alternateColor = palette.color(palette.Base).darker(104) self._borderColor = palette.color(palette.Mid) # create custom properties chartWidget.installEventFilter(self) self.chartTypeChanged.connect(self.update)
def __init__(self, chartWidget): super(XChartScene, self).__init__(chartWidget) # create custom properties self._chartWidget = chartWidget self._minimumWidth = -1 self._minimumHeight = -1 self._maximumWidth = -1 self._maximumHeight = -1 self._horizontalPadding = 6 self._verticalPadding = 6 self._showGrid = True self._showRows = True self._showColumns = True self._trackingEnabled = True self._chartType = XChartScene.Type.Line self._trackerItem = None # used with pie charts self._pieAxis = Qt.YAxis self._pieAlignment = Qt.AlignCenter self._horizontalRuler = XChartRuler(XChartRuler.Type.Number) self._verticalRuler = XChartRuler(XChartRuler.Type.Number) self._font = QApplication.font() self._alternatingColumnColors = False self._alternatingRowColors = True self._dirty = False self._buildData = {} palette = QApplication.palette() self._axisColor = palette.color(palette.Mid).darker(125) self._baseColor = palette.color(palette.Base) self._alternateColor = palette.color(palette.Base).darker(104) self._borderColor = palette.color(palette.Mid) # create custom properties chartWidget.installEventFilter(self) self.chartTypeChanged.connect(self.update)
def capture(rect=None, filepath='', prompt=True, hideWindow=None): """ Prompts the user to capture the screen. :param rect | <QRect> filepath | <str> prompt | <bool> :return (<str> filepath, <bool> accepted) """ widget = XSnapshotWidget(QApplication.desktop()) widget.setRegion(rect) widget.setHideWindow(hideWindow) widget.setFilepath(filepath) widget.move(1, 1) widget.resize(QApplication.desktop().size()) if prompt or not filepath: widget.show() else: widget.save()
def restore(self, viewWidget): """ Applies the profile to the inputed view widget. :param viewWidget | <XViewWidget> """ if self._xmlElement is None: return False # disable all the information viewWidget.blockSignals(True) viewWidget.setUpdatesEnabled(False) viewWidget.setCursor(Qt.WaitCursor) viewWidget.reset(force=True) # make sure all the cleanup happens (short of GUI updates) QApplication.sendPostedEvents() # restore the widget data try: xml_elem = self._xmlElement[0] except IndexError: viewWidget.unsetCursor() viewWidget.blockSignals(False) viewWidget.setUpdatesEnabled(True) return False widget = self.restoreWidget(viewWidget, viewWidget, xml_elem) viewWidget.setWidget(widget) viewWidget.setLocked(self._xmlElement.get('locked') == 'True') # enable the infromation viewWidget.unsetCursor() viewWidget.blockSignals(False) viewWidget.setUpdatesEnabled(True) return True
def apply( self ): """ Applies the scheme to the current application. """ font = self.value('font') try: font.setPointSize(self.value('fontSize')) # errors in linux for some reason except TypeError: pass palette = self.value('colorSet').palette() if ( unwrapVariant(QApplication.instance().property('useScheme')) ): QApplication.instance().setFont(font) QApplication.instance().setPalette(palette) # hack to support MDI Areas for widget in QApplication.topLevelWidgets(): for area in widget.findChildren(QMdiArea): area.setPalette(palette) else: logger.debug('The application doesnt have the useScheme property.')
def apply(self): """ Applies the scheme to the current application. """ font = self.value('font') try: font.setPointSize(self.value('fontSize')) # errors in linux for some reason except TypeError: pass palette = self.value('colorSet').palette() if (unwrapVariant(QApplication.instance().property('useScheme'))): QApplication.instance().setFont(font) QApplication.instance().setPalette(palette) # hack to support MDI Areas for widget in QApplication.topLevelWidgets(): for area in widget.findChildren(QMdiArea): area.setPalette(palette) else: logger.debug('The application doesnt have the useScheme property.')
def getDialog(cls, name, parent=None): """ Generates a dialog for this class widget and returns it. :param parent | <QtGui.QWidget> || None :return <QtGui.QDialog> """ key = '_{0}__{1}_dialog'.format(cls.__name__, name) dlgref = getattr(cls, key, None) if dlgref is not None: dlg = dlgref() if dlg: return dlg if parent is None: parent = QApplication.activeWindow() dlg = QDialog(parent) # create widget widget = cls(dlg) dlg.__dict__['_mainwidget'] = widget widget.layout().setContentsMargins(0, 0, 0, 0) # create buttons opts = QDialogButtonBox.Save | QDialogButtonBox.Cancel buttons = QDialogButtonBox(opts, Qt.Horizontal, dlg) # create layout layout = QVBoxLayout() layout.addWidget(widget) layout.addWidget(buttons) dlg.setLayout(layout) dlg.resize(widget.minimumSize() + QSize(15, 15)) widget.resizeRequested.connect(dlg.adjustSize) # create connections buttons.accepted.connect(widget.save) buttons.rejected.connect(dlg.reject) widget.saved.connect(dlg.accept) widget.setFocus() dlg.adjustSize() if parent and parent.window(): center = parent.window().geometry().center() dlg.move(center.x() - dlg.width() / 2.0, center.y() - dlg.height() / 2.0) setattr(cls, key, weakref.ref(dlg)) return dlg
def refreshCards(self): """ Refreshes the results for the cards view of the browser. """ cards = self.cardWidget() factory = self.factory() self.setUpdatesEnabled(False) self.blockSignals(True) cards.setUpdatesEnabled(False) cards.blockSignals(True) cards.clear() QApplication.instance().processEvents() if self.isGroupingActive(): grouping = self.records().grouped() for groupName, records in sorted(grouping.items()): self._loadCardGroup(groupName, records, cards) else: for record in self.records(): widget = factory.createCard(cards, record) if not widget: continue widget.adjustSize() # create the card item item = QTreeWidgetItem(cards) item.setSizeHint(0, QSize(0, widget.height())) cards.setItemWidget(item, 0, widget) cards.setUpdatesEnabled(True) cards.blockSignals(False) self.setUpdatesEnabled(True) self.blockSignals(False)
def refreshCards( self ): """ Refreshes the results for the cards view of the browser. """ cards = self.cardWidget() factory = self.factory() self.setUpdatesEnabled(False) self.blockSignals(True) cards.setUpdatesEnabled(False) cards.blockSignals(True) cards.clear() QApplication.instance().processEvents() if ( self.isGroupingActive() ): grouping = self.records().grouped() for groupName, records in sorted(grouping.items()): self._loadCardGroup(groupName, records, cards) else: for record in self.records(): widget = factory.createCard(cards, record) if ( not widget ): continue widget.adjustSize() # create the card item item = QTreeWidgetItem(cards) item.setSizeHint(0, QSize(0, widget.height())) cards.setItemWidget(item, 0, widget) cards.setUpdatesEnabled(True) cards.blockSignals(False) self.setUpdatesEnabled(True) self.blockSignals(False)
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
def handleActionTrigger(self, action): """ Handles when an action has been triggered. If the inputed action is a XViewProfileAction, then the currentProfileChanged signal will emit. :param action | <QAction> """ # trigger a particular profile if isinstance(action, XViewProfileAction): # if the user CTRL+Clicks on the action, then attempt # to load it in a new window if QApplication.keyboardModifiers() == Qt.ControlModifier: self.newWindowProfileRequested.emit(action.profile()) self.setCurrentProfile(self.currentProfile()) return else: self.setCurrentProfile(action.profile())
def __init__(self, pixmap): super(XImageItem, self).__init__() # define the mirror instance self._basePixmap = pixmap # set the pixmap palette = QApplication.palette() color = palette.color(palette.Highlight) effect = XGraphicsDropShadowEffect() effect.setOffset(0) effect.setBlurRadius(6) effect.setColor(color) self.setGraphicsEffect(effect) self.graphicsEffect().setEnabled(False) self.setFlags(self.ItemIsSelectable)
def gotoUrl(self, url): try: urlstr = url.toString() except: urlstr = nativestring(url) if not urlstr.endswith('.html'): self.gotoItem(urlstr) return if not QApplication.keyboardModifiers() == Qt.ControlModifier: widget = self.currentContentsWidget(autoadd=True) else: widget = self.addContentsWidget() index = self.uiContentsTAB.indexOf(widget) self.uiContentsTAB.setCurrentIndex(index) widget.setUrl(QUrl(url))
def __init__(self): # define custom properties palette = QApplication.palette() self._name = 'Default' self._axisColor = palette.color(palette.Mid).darker(125) self._alternateColor = palette.color(palette.Base).darker(104) self._baseColor = palette.color(palette.Base) self._borderColor = palette.color(palette.Mid) self._showGrid = True self._showRows = True self._showColumns = True self._showXAxis = True self._showYAxis = True self._verticalLabelPadding = 4 self._horizontalLabelPadding = 4 self._alternatingRowColors = True self._alternatingColumnColors = False self._buildData = {}
def maxNotchSize( self, orientation ): """ Returns the maximum size for this ruler based on its notches and the given orientation. :param orientation | <Qt.Orientation> :return <int> """ metrics = QFontMetrics(QApplication.font()) if orientation == Qt.Vertical: notch = '' for n in self.notches(): if len(nativestring(n)) > len(nativestring(notch)): notch = nativestring(n) return metrics.width(notch) else: return metrics.height()
def gotoHome(self): """ Navigates to the home position for the edit. """ mode = QTextCursor.MoveAnchor # select the home if QApplication.instance().keyboardModifiers() == Qt.ShiftModifier: mode = QTextCursor.KeepAnchor cursor = self.textCursor() block = projex.text.nativestring(cursor.block().text()) cursor.movePosition( QTextCursor.StartOfBlock, mode ) if block.startswith('>>> '): cursor.movePosition(QTextCursor.Right, mode, 4) elif block.startswith('... '): match = re.match('...\s*', block) cursor.movePosition(QTextCursor.Right, mode, match.end()) self.setTextCursor(cursor)
def setCurrentState(self, state): """ Sets the current state for this edit to the inputed state. :param state | <XLineEdit.State> """ self._currentState = state palette = self.palette() if state == XLineEdit.State.Normal: palette = QApplication.instance().palette() elif state == XLineEdit.State.Failed: palette.setColor(palette.Base, QColor('#ffc9bc')) palette.setColor(palette.Text, QColor('#aa2200')) palette.setColor(palette.Disabled, palette.Text, QColor('#e58570')) elif state == XLineEdit.State.Passed: palette.setColor(palette.Base, QColor('#d1ffd1')) palette.setColor(palette.Text, QColor('#00aa00')) palette.setColor(palette.Disabled, palette.Text, QColor('#75e575')) self._hintColor = palette.color(palette.Disabled, palette.Text) self.setPalette(palette)
def __init__( self, query, joiner = '' ): super(XQueryItem, self).__init__() # set the joiner self._joiner = joiner # update the hint self.setText(0, joiner) self.setSizeHint(1, QSize(80, 20)) if ( Q.typecheck(query) ): op_name = Q.Op[query.operatorType()] op_name = projex.text.joinWords(op_name, ' ').lower() palette = QApplication.palette() for i in range(4): self.setBackground(i, palette.color(palette.Base)) self.setTextAlignment(0, Qt.AlignRight | Qt.AlignVCenter) self.setText(1, query.columnName()) self.setText(2, op_name) self.setText(3, query.valueString()) flags = self.flags() flags |= Qt.ItemIsEditable self.setFlags(flags) else: sub_joiner = QueryCompound.Op[query.operatorType()].lower() for i, sub_query in enumerate(query.queries()): if ( i ): item = XQueryItem(sub_query, sub_joiner) else: item = XQueryItem(sub_query) self.addChild(item)
__email__ = '*****@*****.**' #------------------------------------------------------------------------------ # define version information (major,minor,maintanence) __depends__ = ['projex'] __version_info__ = (0, 0, 0) __version__ = '%i.%i.%i' % __version_info__ #------------------------------------------------------------------------------ import projex projex.requires('projexui') from projexui.qt.QtCore import Qt from projexui.qt.QtGui import QApplication from projexui.widgets.xconsoleedit import XConsoleEdit if __name__ == '__main__': app = None if not QApplication.instance(): app = QApplication([]) app.setStyle('plastique') console = XConsoleEdit(QApplication.instance().activeWindow()) console.setWindowTitle('XInterpreter') console.setWindowFlags(Qt.Dialog) console.show() if app: app.exec_()
def applyCommand(self): """ Applies the current line of code as an interactive python command. """ # generate the command information cursor = self.textCursor() cursor.movePosition(cursor.EndOfLine) line = projex.text.nativestring(cursor.block().text()) at_end = cursor.atEnd() modifiers = QApplication.instance().keyboardModifiers() mod_mode = at_end or modifiers == Qt.ShiftModifier # test the line for information if mod_mode and line.endswith(':'): cursor.movePosition(cursor.EndOfLine) line = re.sub('^>>> ', '', line) line = re.sub('^\.\.\. ', '', line) count = len(line) - len(line.lstrip()) + 4 self.insertPlainText('\n... ' + count * ' ') return False elif mod_mode and line.startswith('...') and \ (line.strip() != '...' or not at_end): cursor.movePosition(cursor.EndOfLine) line = re.sub('^\.\.\. ', '', line) count = len(line) - len(line.lstrip()) self.insertPlainText('\n... ' + count * ' ') return False # if we're not at the end of the console, then add it to the end elif line.startswith('>>>') or line.startswith('...'): # move to the top of the command structure line = projex.text.nativestring(cursor.block().text()) while line.startswith('...'): cursor.movePosition(cursor.PreviousBlock) line = projex.text.nativestring(cursor.block().text()) # calculate the command cursor.movePosition(cursor.EndOfLine) line = projex.text.nativestring(cursor.block().text()) ended = False lines = [] while True: # add the new block lines.append(line) if cursor.atEnd(): ended = True break # move to the next line cursor.movePosition(cursor.NextBlock) cursor.movePosition(cursor.EndOfLine) line = projex.text.nativestring(cursor.block().text()) # check for a new command or the end of the command if not line.startswith('...'): break command = '\n'.join(lines) # if we did not end up at the end of the command block, then # copy it for modification if not (ended and command): self.waitForInput() self.insertPlainText(command.replace('>>> ', '')) cursor.movePosition(cursor.End) return False else: self.waitForInput() return False self.executeCommand(command) return True
def __init__( self, *args, **defaults ): defaults.setdefault('colorSet', XPaletteColorSet()) defaults.setdefault('font', QApplication.font()) defaults.setdefault('fontSize', QApplication.font().pointSize()) super(XScheme, self).__init__( *args, **defaults )