def __init__(self, parent): ''' This label is managed from PMXMessageOverlay mixin, should not be used outside this module ''' QtGui.QLabel.__init__(self, parent) self.setStyleSheet(self.STYLESHEET) self.linkActivated.connect(self.linkHandler) self.goe = QtGui.QGraphicsOpacityEffect(self) self.setGraphicsEffect(self.goe) self.timeoutTimer = QtCore.QTimer(self) self.timeoutTimer.setSingleShot(True) self.animationIn = QtCore.QPropertyAnimation(self.goe, "opacity") self.animationIn.setDuration(300) self.animationIn.setStartValue(0) self.animationIn.setEndValue(1.0) self.animationIn.finished.connect(self.timeoutTimer.start) self.animationOut = QtCore.QPropertyAnimation(self.goe, "opacity") self.animationOut.setDuration(300) self.animationOut.setStartValue(1.0) self.animationOut.setEndValue(0) self.animationOut.finished.connect(self.hide) self.timeoutTimer.timeout.connect(self.animationOut.start) self.hide()
def _grep_file(self, file_path): if not self.by_phrase: with open(file_path, 'r') as f: #TODO: Ver mejor el tema de unicode content = f.read().decode("utf-8") words = [word for word in self.searchPattern.split('|')] words.insert(0, True) def check_whole_words(result, word): return result and content.find(word) != -1 if not reduce(check_whole_words, words): return file_object = QtCore.QFile(file_path) if not file_object.open(QtCore.QFile.ReadOnly): return stream = QtCore.QTextStream(file_object) lines = [] line_index = 1 line = stream.readLine() while not self._cancel: column = line.find(self.searchPattern) if column != -1: lines.append((line_index, line)) #take the next line! line = stream.readLine() if stream.atEnd(): break line_index += 1 #emit a signal! self.foundPattern.emit(file_path, lines)
def resizeEvent(self, event): q = self.parentWidget() fw = q.isFloating() and q.style().pixelMetric( QtGui.QStyle.PM_DockWidgetFrameWidth, None, q) or 0 opt = QtGui.QStyleOptionDockWidgetV2() opt.initFrom(q) opt.rect = QtCore.QRect( QtCore.QPoint(fw, fw), QtCore.QSize(self.geometry().width() - (fw * 2), self.geometry().height() - (fw * 2))) opt.title = q.windowTitle() opt.closable = hasFeature(q, QtGui.QDockWidget.DockWidgetClosable) opt.floatable = hasFeature(q, QtGui.QDockWidget.DockWidgetFloatable) floatRect = q.style().subElementRect( QtGui.QStyle.SE_DockWidgetFloatButton, opt, q) if not floatRect.isNull(): self.floatButton.setGeometry(floatRect) closeRect = q.style().subElementRect( QtGui.QStyle.SE_DockWidgetCloseButton, opt, q) if not closeRect.isNull(): self.closeButton.setGeometry(closeRect) top = fw if not floatRect.isNull(): top = floatRect.y() elif not closeRect.isNull(): top = closeRect.y() size = self.collapseButton.size() if not closeRect.isNull(): size = self.closeButton.size() elif not floatRect.isNull(): size = self.floatButton.size() collapseRect = QtCore.QRect(QtCore.QPoint(fw, top), size) self.collapseButton.setGeometry(collapseRect)
def _focus_changed(self, old, new): """ Handle a change in focus that affects the current tab. """ # It is possible for the C++ layer of this object to be deleted between # the time when the focus change signal is emitted and time when the # slots are dispatched by the Qt event loop. This may be a bug in PyQt4. if sip.isdeleted(self): return if self._repeat_focus_changes: self.emit(QtCore.SIGNAL('focusChanged(QWidget *,QWidget *)'), old, new) if isinstance(new, _DragableTabBar): ntw = new.parent() ntidx = ntw.currentIndex() else: ntw, ntidx = self._tab_widget_of(new) if ntw is not None: self._set_current_tab(ntw, ntidx) # See if the widget that has lost the focus is ours. otw, _ = self._tab_widget_of(old) if otw is not None or ntw is not None: if ntw is None: nw = None else: nw = ntw.widget(ntidx) self.emit(QtCore.SIGNAL('hasFocus'), nw)
def create_menu(parent, settings, useSeparatorName=False, connectActions=False): text = settings.get("text", "Menu") menu = QtGui.QMenu(text, parent) menu.setObjectName(text2objectname(text, prefix="menu")) # attrs if settings.has_key("icon"): icon = settings["icon"] if isinstance(icon, basestring): icon = resources.getIcon(icon) menu.setIcon(icon) # actions actions = extend_menu(menu, settings.get("items", []), useSeparatorName) if connectActions: for action in actions: if hasattr(action, 'callback'): if action.isCheckable(): parent.connect(action, QtCore.SIGNAL('triggered(bool)'), action.callback) else: parent.connect(action, QtCore.SIGNAL('triggered()'), action.callback) return menu, actions
def sizeHint(self): self.ensurePolished() margin = self.style().pixelMetric( QtGui.QStyle.PM_DockWidgetTitleBarButtonMargin, None, self) if self.icon().isNull(): return QtCore.QSize(margin, margin) iconSize = self.style().pixelMetric(QtGui.QStyle.PM_SmallIconSize, None, self) pm = self.icon().pixmap(iconSize) return QtCore.QSize(pm.width() + margin, pm.height() + margin)
def replaceSysExceptHook(self): # Exceptions, Print exceptions in a window def displayExceptionDialog(exctype, value, traceback): ''' Display a nice dialog showing the python traceback''' from prymatex.gui.emergency.tracedialog import PMXTraceBackDialog sys.__excepthook__(exctype, value, traceback) PMXTraceBackDialog.fromSysExceptHook(exctype, value, traceback).exec_() sys.excepthook = displayExceptionDialog # Route messages to application logger QtCore.qInstallMsgHandler(self.qtMessageHandler)
def __init__(self, name): profile, created = self.get_or_create_profile(name) self.PMX_PROFILE_NAME = profile["name"] self.PMX_PROFILE_PATH = profile["path"] self.PMX_TMP_PATH = os.path.join(self.PMX_PROFILE_PATH, 'tmp') self.PMX_LOG_PATH = os.path.join(self.PMX_PROFILE_PATH, 'log') self.PMX_CACHE_PATH = os.path.join(self.PMX_PROFILE_PATH, 'cache') self.PMX_SCREENSHOT_PATH = os.path.join(self.PMX_PROFILE_PATH, 'screenshot') self.GROUPS = {} self.qsettings = QtCore.QSettings(os.path.join(self.PMX_PROFILE_PATH, self.PMX_SETTING_NAME), QtCore.QSettings.IniFormat) self.tmsettings = TextMateSettings(os.path.join(self.PMX_PREFERENCES_PATH, self.TM_SETTINGS_NAME)) self.state = QtCore.QSettings(os.path.join(self.PMX_PROFILE_PATH, self.PMX_STATE_NAME), QtCore.QSettings.IniFormat)
def __init__(self, pixmap): QtGui.QSplashScreen.__init__(self, pixmap) self.defaultAlignment = QtCore.Qt.AlignCenter self.defaultColor = QtCore.Qt.black self.shadowColor = QtGui.QColor(QtCore.Qt.black) self.shadowColor.setAlpha(128) self.message = "" self.color = self.alignment = None self.textRect = QtCore.QRect(self.rect().x() + 100, self.rect().y() + 510, 260, 50) self.shadowTextRect = QtCore.QRect(self.rect().x() + 101, self.rect().y() + 511, 260, 50)
def on_sourceModel_dataChanged(self, topLeft, bottomRight): #Cambiaron los datos tengo que ponerlos en funcion del comparableValue if topLeft in self.__indexMap: self.beginRemoveRows(QtCore.QModelIndex(), self.__indexMap.index(topLeft), self.__indexMap.index(topLeft)) self.__indexMap.remove(topLeft) self.endRemoveRows() position = bisect_key(self.__indexMap, topLeft, lambda index: self.comparableValue(index)) self.beginInsertRows(QtCore.QModelIndex(), position, position) self.__indexMap.insert(position, topLeft) self.endInsertRows()
def __init__(self, parent, url, operation): super(TmFileReply, self).__init__(parent) file = codecs.open(url.path(), 'r', 'utf-8') self.content = file.read().encode('utf-8') self.offset = 0 self.setHeader(QNetworkRequest.ContentTypeHeader, "text/html; charset=utf-8") self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.content)) QtCore.QTimer.singleShot(0, self, QtCore.SIGNAL("readyRead()")) QtCore.QTimer.singleShot(0, self, QtCore.SIGNAL("finished()")) self.open(self.ReadOnly | self.Unbuffered) self.setUrl(url)
def index(self, row, column, parentIndex): parentNode = self.node(parentIndex) childNode = parentNode.child(row) if childNode is not None: return self.createIndex(row, column, childNode) else: return QtCore.QModelIndex()
def data(self, index, role): if self.__sourceModel is None: return QtCore.QVariant() sIndex = self.mapToSource(index) return self.__sourceModel.data(sIndex, role)
def on_pushButtonUp_pressed(self): index = self.treeViewFileSystem.rootIndex() sIndex = self.fileSystemProxyModel.mapToSource(index) dir = QtCore.QDir(self.fileSystemModel.filePath(sIndex)) if dir.cdUp(): self.setPathAsRoot(dir.path()) self.comboBoxLocation.lineEdit().setText(dir.path())
class ConfigureTreeModel(ConfigureTreeModelBase): proxyConfigureCreated = QtCore.pyqtSignal(object) def treeNodeFactory(self, nodeName, nodeParent=None): proxy = ProxyConfigureTreeNode(nodeName, nodeParent) self.proxyConfigureCreated.emit(proxy) return proxy
class SystemWrapper(QtCore.QObject): def __init__(self, process, file): QtCore.QObject.__init__(self) self.process = process self.file = file @QtCore.pyqtSlot(str) def write(self, data): self.process.stdin.write(data) @QtCore.pyqtSlot() def read(self): self.process.stdin.close() text = self.process.stdout.read() self.process.stdout.close() self.process.wait() deleteFile(self.file) return text @QtCore.pyqtSlot() def close(self): self.process.stdin.close() self.process.stdout.close() self.process.wait() deleteFile(self.file) def outputString(self): self.process.stdin.close() text = self.process.stdout.read() self.process.stdout.close() self.process.wait() deleteFile(self.file) return text outputString = QtCore.pyqtProperty(str, outputString)
def get_icon(index, default=None): ''' Makes the best effort to find an icon for an index. Index can be a path, a Qt resource path, an integer. @return: QIcon instance or None if no icon could be retrieved ''' #Try icon in db path = getResourcePath(index, ["Icons", "External"]) if path is not None: return QtGui.QIcon(path) elif isinstance(index, basestring): #Try file path if os.path.isfile(index): return __fileIconProvider.icon(QtCore.QFileInfo(index)) elif os.path.isdir(index): return __fileIconProvider.icon(QtGui.QFileIconProvider.Folder) elif QtGui.QIcon.hasThemeIcon(index): return QtGui.QIcon._fromTheme(index) elif default is not None: return default else: return QtGui.QIcon(getResourcePath("notfound", ["Icons"])) elif isinstance(index, int): #Try icon by int index in fileicon provider return __fileIconProvider.icon(index)
def __init__(self, name, area, parent): QtGui.QToolBar.__init__(self, parent) assert isinstance(parent, QtGui.QMainWindow) assert area in self.DOCK_AREA_TO_TB self._area = area self.setObjectName(text2objectname(name, prefix="ToolBar")) self.setWindowTitle(name) #Button Style #self.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.setFloatable(False) self.setMovable(False) self.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.MinimumExpanding)) self.setIconSize(QtCore.QSize(16, 16)) #Restore action self.restoreAction = QtGui.QAction(self) self.restoreAction.setIcon(resources.getIcon("image-stack")) self.restoreAction.triggered.connect(self.hide) self.addAction(self.restoreAction) self.visibilityChanged.connect(self.on_visibilityChanged)
def __init__(self, parent): QtGui.QPlainTextEdit.__init__(self, parent) font = self.document().defaultFont() font.setPixelSize(1) self.document().setDefaultFont(font) self.setWordWrapMode(QtGui.QTextOption.NoWrap) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setReadOnly(True) self.setCenterOnScroll(True) self.setMouseTracking(True) self.viewport().setCursor(QtCore.Qt.PointingHandCursor) self.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) self.editor = None self.highlighter = None self.lines_count = 0 self.goe = QtGui.QGraphicsOpacityEffect() self.setGraphicsEffect(self.goe) self.goe.setOpacity(50) self.animation = QtCore.QPropertyAnimation(self.goe, "opacity") self.slider = SliderArea(self) self.slider.show() self.setFixedWidth(60)
def paintEvent(self, event): p = QtGui.QPainter(self) r = self.rect() opt = QtGui.QStyleOptionToolButton() opt.init(self) opt.state |= QtGui.QStyle.State_AutoRaise if self.isEnabled() and self.underMouse() and \ not self.isChecked() and not self.isDown(): opt.state |= QtGui.QStyle.State_Raised if self.isChecked(): opt.state |= QtGui.QStyle.State_On if self.isDown(): opt.state |= QtGui.QStyle.State_Sunken self.style().drawPrimitive(QtGui.QStyle.PE_PanelButtonTool, opt, p, self) opt.icon = self.icon() opt.subControls = QtGui.QStyle.SubControls() opt.activeSubControls = QtGui.QStyle.SubControls() opt.features = QtGui.QStyleOptionToolButton.None opt.arrowType = QtCore.Qt.NoArrow size = self.style().pixelMetric(QtGui.QStyle.PM_SmallIconSize, None, self) opt.iconSize = QtCore.QSize(size, size) self.style().drawComplexControl(QtGui.QStyle.CC_ToolButton, opt, p, self)
class CodeEditorSideBar(QtGui.QWidget): updateRequest = QtCore.pyqtSignal() def __init__(self, editor): QtGui.QWidget.__init__(self, editor) self.editor = editor self.horizontalLayout = QtGui.QHBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) def addWidget(self, widget): self.horizontalLayout.addWidget(widget) widget.installEventFilter(self) def eventFilter(self, obj, event): if event.type() in [ QtCore.QEvent.Hide, QtCore.QEvent.Show ]: self.updateRequest.emit() return True return QtCore.QObject.eventFilter(self, obj, event) def width(self): width = 0 for index in range(self.horizontalLayout.count()): widget = self.horizontalLayout.itemAt(index).widget() if widget.isVisible(): width += widget.width() return width def scroll(self, *largs): for index in range(self.horizontalLayout.count()): self.horizontalLayout.itemAt(index).widget().scroll(*largs)
def paint(self, glyph, painter, rect, mode, state, options): painter.save() #set the correct color color = options.get("color") text = options.get("text") if mode == QtGui.QIcon.Disabled: color = options.get("color-disabled") alt = options.get("text-disabled") if alt: text = "%s" % alt elif mode == QtGui.QIcon.Active: color = options.get("color-active") alt = options.get("text-active") if alt: text = "%s" % alt elif mode == QtGui.QIcon.Selected: color = options.get("color-selected") alt = options.get("text-selected") if alt: text = "%s" % alt painter.setPen(color) # add some 'padding' around the icon drawSize = QtCore.qRound(rect.height() * options.get("scale-factor")) painter.setFont(glyph.font(drawSize)) painter.drawText(rect, QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter, text) painter.restore()
def addTab(self, w): """ Add a new tab to the main tab widget. """ ch = self._tabParentCreateRequest if ch is None: # Find the first tab widget going down the left of the hierarchy. This # will be the one in the top left corner. if self.count() > 0: ch = self.widget(0) while not isinstance(ch, _TabWidget): assert isinstance(ch, QtGui.QSplitter) ch = ch.widget(0) else: # There is no tab widget so create one. ch = _TabWidget(self) self.addWidget(ch) idx = ch.addTab(w, self.disambiguatedWidgetTitle(w)) self.setWidgetToolTip(w, w.tabToolTip()) self.setWidgetIcon(w, w.tabIcon()) self.connect(w, QtCore.SIGNAL("tabStatusChanged()"), self._update_tab_status) # If the tab has been added to the current tab widget then make it the # current tab. if ch is not self._current_tab_w: self._set_current_tab(ch, idx) ch.tabBar().setFocus()
def __init__(self, application): QtCore.QObject.__init__(self) self.last_directory = get_home_dir() self.fileWatcher = QtCore.QFileSystemWatcher() self.fileWatcher.fileChanged.connect(self.on_fileChanged) self.fileWatcher.directoryChanged.connect(self.on_directoryChanged) self.connectGenericSignal()
def show(self, dialog): """Generic method to show a non-modal dialog and keep reference to the QtCore.Qt C++ object""" for dlg in self.dialogs.values(): if unicode(dlg.windowTitle()) == unicode(dialog.windowTitle()): dlg.show() dlg.raise_() break else: dialog.show() self.dialogs[id(dialog)] = dialog self.connect(dialog, QtCore.SIGNAL('accepted()'), lambda eid=id(dialog): self.dialog_finished(eid)) self.connect(dialog, QtCore.SIGNAL('rejected()'), lambda eid=id(dialog): self.dialog_finished(eid))
def appendProcess(self, process, description=""): self.beginInsertRows(QtCore.QModelIndex(), len(self.processItems), len(self.processItems)) self.processItems.append({ "process": process, "description": description }) self.endInsertRows()
def parent(self, index): node = self.node(index) parentNode = node.nodeParent() # Todo ver si puede llegar como index el root porque algo en este if no esta bien if parentNode is None or parentNode.isRootNode(): return QtCore.QModelIndex() return self.createIndex(parentNode.row(), parentNode.column(), parentNode)
def initialize(self, editor): CodeEditorAddon.initialize(self, editor) if self.dictionary is not None: editor.registerTextCharFormatBuilder( "spell", self.textCharFormat_spell_builder) editor.syntaxReady.connect(self.on_editor_syntaxReady) self.connect(editor, QtCore.SIGNAL("keyPressEvent(QEvent)"), self.on_editor_keyPressEvent)
def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) PMXBaseDialog.__init__(self) self.setupUi(self) self.progressAnimate = False self.animateTimer = QtCore.QTimer(self) self.animateTimer.timeout.connect(self.updateProgressValue) self.currentProgressValue = 0 self.milestoneProgressValue = 0
def create_action(parent, settings): """Create a QAction""" text = settings.get("text", "Action") action = QtGui.QAction(text, parent) action.setObjectName(text2objectname(text, prefix="action")) # attrs if settings.has_key("icon"): icon = settings["icon"] if isinstance(icon, basestring): icon = resources.getIcon(icon) action.setIcon(icon) if settings.has_key("shortcut"): action.setShortcut(settings["shortcut"]) if settings.has_key("tip"): action.setToolTip(settings["tip"]) action.setStatusTip(settings["tip"]) if settings.has_key("data"): action.setData(settings["data"]) if settings.has_key("menurole"): action.setMenuRole(settings["menurole"]) if settings.has_key("checkable"): action.setCheckable(settings["checkable"]) # callables if settings.has_key("callback"): action.callback = settings["callback"] if settings.has_key("testChecked"): action.testChecked = settings["testChecked"] if settings.has_key("triggered") and callable(settings["triggered"]): parent.connect(action, QtCore.SIGNAL("triggered()"), settings["triggered"]) if settings.has_key("toggled") and callable(settings["toggled"]): parent.connect(action, QtCore.SIGNAL("toggled(bool)"), settings["toggled"]) action.setCheckable(True) #TODO: Hard-code all shortcuts and choose context=QtCore.Qt.WidgetShortcut # (this will avoid calling shortcuts from another dockwidget # since the context thing doesn't work quite well with these widgets) action.setShortcutContext(settings.get("context", QtCore.Qt.WindowShortcut)) return action
def paintEvent(self, event): p = QtGui.QStylePainter(self) q = self.parentWidget() fw = q.isFloating() and q.style().pixelMetric( QtGui.QStyle.PM_DockWidgetFrameWidth, None, q) or 0 mw = q.style().pixelMetric(QtGui.QStyle.PM_DockWidgetTitleMargin, None, q) titleOpt = QtGui.QStyleOptionDockWidgetV2() titleOpt.initFrom(q) titleOpt.rect = QtCore.QRect(QtCore.QPoint(fw + mw + self.collapseButton.size().width(), fw), QtCore.QSize( self.geometry().width() - (fw * 2) - \ mw - self.collapseButton.size().width(), self.geometry().height() - (fw * 2))) titleOpt.title = q.windowTitle() titleOpt.closable = hasFeature(q, QtGui.QDockWidget.DockWidgetClosable) titleOpt.floatable = hasFeature(q, QtGui.QDockWidget.DockWidgetFloatable) p.drawControl(QtGui.QStyle.CE_DockWidgetTitle, titleOpt)
def __init__(self, root, tab_bar, tab, start_pos): """ Initialise the instance. """ self.dragging = False self._root = root self._tab_bar = tab_bar self._tab = tab self._start_pos = QtCore.QPoint(start_pos) self._clone = None