def SetItems(parentItem, fictiveObjects, level): level += 1 for object in fictiveObjects: type = object.type if not type in showTypes: continue # Construct text if type in ('cell', '##', '#%%', '# %%'): type = 'cell:' elif type == 'attribute': type = 'attr' # if type == 'import': text = "%s (%s)" % (object.name, object.text) elif type == 'todo': text = object.name else: text = "%s %s" % (type, object.name) # Create item thisItem = QtWidgets.QTreeWidgetItem(parentItem, [text]) color = QtGui.QColor(colours[object.type]) thisItem.setForeground(0, QtGui.QBrush(color)) font = thisItem.font(0) font.setBold(True) thisItem.setFont(0, font) thisItem.linenr = object.linenr # Is this the current item? if ln and object.linenr <= ln and object.linenr2 > ln: selectedItem[0] = thisItem # Any children that we should display? if object.children: SetItems(thisItem, object.children, level) # Set visibility thisItem.setExpanded(bool(level < showLevel))
def __init__(self, parent, distro=None): QtGui.QWidget.__init__(self, parent) self.setMinimumSize(360, 256) # Ensure title fits nicely # Create label widget and costumize self._label = QtGui.QLabel(self) self._label.setTextFormat(QtCore.Qt.RichText) self._label.setOpenExternalLinks(True) self._label.setWordWrap(True) self._label.setMargin(20) # Set font size (absolute value) font = self._label.font() font.setPointSize(11) #(font.pointSize()+1) self._label.setFont(font) # Build distrotext = '' if distro: distrotext = '<br />brought to you by %s.' % distro text = splash_text.format(distro=distrotext, version=pyzo.__version__) # Set text self._label.setText(text) layout = QtGui.QVBoxLayout(self) self.setLayout(layout) layout.addStretch(1) layout.addWidget(self._label, 0) layout.addStretch(1)
def __init__(self, parent, i): QtGui.QWizardPage.__init__(self, parent) self._i = i # Create label for description self._text_label = QtGui.QLabel(self) self._text_label.setTextFormat(QtCore.Qt.RichText) self._text_label.setWordWrap(True) # Create label for image self._comicLabel = QtGui.QLabel(self) pm = QtGui.QPixmap() if 'logo' in self._image_filename: pm.load( os.path.join(pyzo.pyzoDir, 'resources', 'appicons', self._image_filename)) elif self._image_filename: pm.load( os.path.join(pyzo.pyzoDir, 'resources', 'images', self._image_filename)) self._comicLabel.setPixmap(pm) self._comicLabel.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) # Layout theLayout = QtGui.QVBoxLayout(self) self.setLayout(theLayout) # theLayout.addWidget(self._text_label) theLayout.addStretch() theLayout.addWidget(self._comicLabel) theLayout.addStretch()
def loadAppIcons(): """ loadAppIcons() Load the application iconsr. """ # Get directory containing the icons appiconDir = os.path.join(pyzo.pyzoDir, "resources", "appicons") # Determine template for filename of the application icon-files. fnameT = "pyzologo{}.png" # Construct application icon. Include a range of resolutions. Note that # Qt somehow does not use the highest possible res on Linux/Gnome(?), even # the logo of qt-designer when alt-tabbing looks a bit ugly. pyzo.icon = QtGui.QIcon() for sze in [16, 32, 48, 64, 128, 256]: fname = os.path.join(appiconDir, fnameT.format(sze)) if os.path.isfile(fname): pyzo.icon.addFile(fname, QtCore.QSize(sze, sze)) # Set as application icon. This one is used as the default for all # windows of the application. QtWidgets.qApp.setWindowIcon(pyzo.icon) # Construct another icon to show when the current shell is busy artist = IconArtist(pyzo.icon) # extracts the 16x16 version artist.setPenColor("#0B0") for x in range(11, 16): d = x - 11 # runs from 0 to 4 artist.addLine(x, 6 + d, x, 15 - d) pm = artist.finish().pixmap(16, 16) # pyzo.iconRunning = QtGui.QIcon(pyzo.icon) pyzo.iconRunning.addPixmap(pm) # Change only 16x16 icon
def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Install a conda env?') self.setModal(True) text = 'Pyzo is only an editor. To execute code, you need a Python environment.\n\n' text += 'Do you want Pyzo to install a Python environment (miniconda)?\n' text += 'If not, you must arrange for a Python interpreter yourself' if not sys.platform.startswith('win'): text += ' or use the system Python' text += '.' text += '\n(You can always launch the installer from the shell menu.)' self._label = QtGui.QLabel(text, self) self._no = QtGui.QPushButton("No thanks (dont ask again)") self._yes = QtGui.QPushButton("Yes, please install Python!") self._no.clicked.connect(self.reject) self._yes.clicked.connect(self.accept) vbox = QtGui.QVBoxLayout(self) hbox = QtGui.QHBoxLayout() self.setLayout(vbox) vbox.addWidget(self._label, 1) vbox.addLayout(hbox, 0) hbox.addWidget(self._no, 2) hbox.addWidget(self._yes, 2) self._yes.setDefault(1)
def _print(self): """Generate the pdf for preview and export""" if self.editor is not None: cursor = self.editor.textCursor() cursor.movePosition(cursor.Start) cursor.movePosition(cursor.End, cursor.KeepAnchor) cursor.insertText(pyzo.editors.getCurrentEditor().toPlainText()) self._set_zoom(self.zoom_selected) # Print with line numbers lines = self.editor.toPlainText().splitlines() nzeros = len(str(len(lines))) self._apply_syntax_highlighting() starting_line = 0 self._change_orientation() # Print name or filename in the editor if self.combobox_file_name.currentIndex(): starting_line = 1 if self.combobox_file_name.currentIndex() == 1: lines.insert(0, '# ' + self.editor_name + '\n') elif self.combobox_file_name.currentIndex() == 2: lines.insert(0, '# ' + self.editor_filename + '\n') # Print line numbers in the editor if self.show_line_number: for i in range(starting_line, len(lines)): lines[i] = str(i+1-starting_line).rjust(nzeros, '0') \ + '| ' + lines[i] cursor = self.editor.textCursor() cursor.movePosition(cursor.Start) cursor.movePosition(cursor.End, cursor.KeepAnchor) cursor.insertText('\n'.join(lines)) # Highlight line numbers if self.show_line_number: cursor.movePosition(cursor.Start, cursor.MoveAnchor) # Move the cursor down 2 lines if a title is printed if starting_line != 0: cursor.movePosition(cursor.NextBlock, cursor.MoveAnchor, 2) # Apply background for lines numbers for i in range(len(lines)): fmt = QtGui.QTextCharFormat() fmt.setBackground(QtGui.QColor(240, 240, 240)) cursor.movePosition(cursor.Right, cursor.KeepAnchor, nzeros) cursor.setCharFormat(fmt) cursor.movePosition(cursor.NextBlock, cursor.MoveAnchor) cursor.movePosition(cursor.StartOfBlock, cursor.MoveAnchor)
def setPenColor(self, color): """ setPenColor(color) Set the color of the pen. Color can be anything that can be passed to Qcolor(). """ pen = QtGui.QPen() if isinstance(color, tuple): pen.setColor(QtGui.QColor(*color)) else: pen.setColor(QtGui.QColor(color)) self._painter.setPen(pen)
def __init__(self, parent): # Do not pass parent, because is a sublayout QtGui.QVBoxLayout.__init__(self) # Create sub-widget self._edit1 = QtGui.QLineEdit(parent) self._edit1.textEdited.connect(self.onEditChanged) if sys.platform.startswith('win'): self._edit1.setPlaceholderText('C:\\path\\to\\script.py') else: self._edit1.setPlaceholderText('/path/to/script.py') # self._edit2 = QtGui.QTextEdit(parent) self._edit2.zoomOut(1) self._edit2.setMaximumHeight(80) self._edit2.setMinimumWidth(200) self._edit2.textChanged.connect(self.onEditChanged) # Layout self.setSpacing(1) self.addWidget(self._edit1) self.addWidget(self._edit2) # Create radio widget for system default t = translate('shell', 'Use system default') self._radio_system = QtGui.QRadioButton(t, parent) self._radio_system.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_system) if self.DISABLE_SYSTEM_DEFAULT: self._radio_system.hide() # Create radio widget for file t = translate('shell', 'File to run at startup') self._radio_file = QtGui.QRadioButton(t, parent) self._radio_file.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_file) # Create radio widget for code t = translate('shell', 'Code to run at startup') self._radio_code = QtGui.QRadioButton(t, parent) self._radio_code.toggled.connect(self.onCheckChanged) self.addWidget(self._radio_code) # The actual value of this shell config attribute self._value = '' # A buffered version, so that clicking the text box does not # remove the value at once self._valueFile = '' self._valueCode = '\n'
def __init__(self, parent): super().__init__(parent) self._label = QtGui.QLabel('hello world') self._label.setTextFormat(QtCore.Qt.RichText) self._label.setWordWrap(True) # self._label.setOpenExternalLinks(True) self._label.linkActivated.connect(self.handle_link) font = self._label.font() font.setPointSize(font.pointSize() + 1) self._label.setFont(font) layout = QtGui.QVBoxLayout() self.setLayout(layout) layout.addWidget(self._label, 1)
def SetItems(parentItem, fictiveObjects, level): level += 1 for object in fictiveObjects: type = object.type if type not in showTypes and type != "nameismain": continue # Construct text if type == "import": text = "ā %s (%s)" % (object.name, object.text) elif type == "todo": text = object.name elif type == "nameismain": text = object.text elif type == "class": text = object.name elif type == "def": text = object.name + "()" elif type == "attribute": text = "- " + object.name elif type in ("cell", "##", "#%%", "# %%"): type = "cell" text = "## " + object.name + " " * 120 else: text = "%s %s" % (type, object.name) # Create item thisItem = QtWidgets.QTreeWidgetItem(parentItem, [text]) color = QtGui.QColor(colours[object.type]) bold = bolds[object.type] thisItem.setForeground(0, QtGui.QBrush(color)) font = thisItem.font(0) if bold == "yes": font.setBold(True) else: font.setBold(False) if type == "cell": font.setUnderline(True) thisItem.setFont(0, font) thisItem.linenr = object.linenr # Is this the current item? if ln and object.linenr <= ln and object.linenr2 > ln: selectedItem[0] = thisItem # Any children that we should display? if object.children: SetItems(thisItem, object.children, level) # Set visibility thisItem.setExpanded(bool(level < showLevel))
def __init__(self, parent): QtWidgets.QWizard.__init__(self, parent) # Set some appearance stuff self.setMinimumSize(600, 500) self.setWindowTitle(translate('wizard', 'Getting started with Pyzo')) self.setWizardStyle(self.ModernStyle) self.setButtonText(self.CancelButton, 'Stop') # Set logo pm = QtGui.QPixmap() pm.load( os.path.join(pyzo.pyzoDir, 'resources', 'appicons', 'pyzologo48.png')) self.setPixmap(self.LogoPixmap, pm) # Define pages klasses = [ IntroWizardPage, TwocomponentsWizardPage, EditorWizardPage, ShellWizardPage1, ShellWizardPage2, RuncodeWizardPage1, RuncodeWizardPage2, ToolsWizardPage1, ToolsWizardPage2, FinalPage ] # Create pages self._n = len(klasses) for i, klass in enumerate(klasses): self.addPage(klass(self, i))
def loadIcons(): """ loadIcons() Load all icons in the icon dir. """ # Get directory containing the icons iconDir = os.path.join(pyzo.pyzoDir, "resources", "icons") # Construct other icons dummyIcon = IconArtist().finish() pyzo.icons = ssdf.new() for fname in os.listdir(iconDir): if fname.endswith(".png"): try: # Short and full name name = fname.split(".")[0] name = name.replace("pyzo_", "") # discart prefix ffname = os.path.join(iconDir, fname) # Create icon icon = QtGui.QIcon() icon.addFile(ffname, QtCore.QSize(16, 16)) # Store pyzo.icons[name] = icon except Exception as err: pyzo.icons[name] = dummyIcon print("Could not load icon %s: %s" % (fname, str(err)))
def getCrossIcon2(self): if hasattr(self, '_cross2'): pm = self._cross2 else: pm = self._createCrossPixmap(240) # Set return QtGui.QIcon(pm)
def onLanguageChange(self): languageName = self._langBox.currentText() if pyzo.config.settings.language == languageName: return # Save new language pyzo.config.settings.language = languageName setLanguage(pyzo.config.settings.language) # Notify user text = translate( 'wizard', """ The language has been changed for this wizard. Pyzo needs to restart for the change to take effect application-wide. """) m = QtGui.QMessageBox(self) m.setWindowTitle(translate("wizard", "Language changed")) m.setText(text) m.setIcon(m.Information) m.exec_() # Get props of current wizard geo = self.wizard().geometry() parent = self.wizard().parent() # Close ourself! self.wizard().close() # Start new one w = PyzoWizard(parent) w.setGeometry(geo) w.show()
def __init__(self, parent): QtGui.QTreeWidget.__init__(self, parent) self._config = parent._config # Set header stuff self.setHeaderHidden(False) self.setColumnCount(3) self.setHeaderLabels(['Name', 'Type', 'Repr']) #self.setColumnWidth(0, 100) self.setSortingEnabled(True) # Nice rows self.setAlternatingRowColors(True) self.setRootIsDecorated(False) # Create proxy self._proxy = WorkspaceProxy() self._proxy.haveNewData.connect(self.fillWorkspace) # For menu self.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self._menu = QtGui.QMenu() self._menu.triggered.connect(self.contextMenuTriggered) # Bind to events self.itemActivated.connect(self.onItemExpand)
def loadFonts(): """ loadFonts() Load all fonts that come with Pyzo. """ import pyzo.codeeditor # we need pyzo and codeeditor namespace here # Get directory containing the icons fontDir = os.path.join(pyzo.pyzoDir, "resources", "fonts") # Get database object db = QtGui.QFontDatabase() # Set default font pyzo.codeeditor.Manager.setDefaultFontFamily("DejaVu Sans Mono") # Load fonts that are in the fonts directory if os.path.isdir(fontDir): for fname in os.listdir(fontDir): if "oblique" in fname.lower(): # issue #461 continue if os.path.splitext(fname)[1].lower() in [".otf", ".ttf"]: try: db.addApplicationFont(os.path.join(fontDir, fname)) except Exception as err: print("Could not load font %s: %s" % (fname, str(err)))
def __init__(self, icon=None): # Get pixmap from given icon (None creates empty pixmap) self._pm = self._getPixmap(icon) # Instantiate painter for the pixmap self._painter = QtGui.QPainter() self._painter.begin(self._pm)
def __init__(self, parent, i): BasePyzoWizardPage.__init__(self, parent, i) # Create label and checkbox t1 = translate('wizard', "This wizard can be opened using 'Help > Pyzo wizard'") t2 = translate('wizard', "Show this wizard on startup") self._label_info = QtGui.QLabel(t1, self) #self._check_show = QtGui.QCheckBox(t2, self) #self._check_show.stateChanged.connect(self._setNewUser) # Create language switcher self._langLabel = QtGui.QLabel(translate('wizard', "Select language"), self) # self._langBox = QtGui.QComboBox(self) self._langBox.setEditable(False) # Fill index, theIndex = -1, -1 cur = pyzo.config.settings.language for lang in sorted(LANGUAGES): index += 1 self._langBox.addItem(lang) if lang == LANGUAGE_SYNONYMS.get(cur, cur): theIndex = index # Set current index if theIndex >= 0: self._langBox.setCurrentIndex(theIndex) # Bind signal self._langBox.activated.connect(self.onLanguageChange) # Init check state #if pyzo.config.state.newUser: # self._check_show.setCheckState(QtCore.Qt.Checked) # Create sublayout layout = QtGui.QHBoxLayout() layout.addWidget(self._langLabel, 0) layout.addWidget(self._langBox, 0) layout.addStretch(2) self.layout().addLayout(layout) # Add to layout self.layout().addSpacing(10) self.layout().addWidget(self._label_info)
def __init__(self, parent): QtGui.QWidget.__init__(self, parent) # Create text field, checkbox, and button self._text = QtGui.QLineEdit(self) self._printBut = QtGui.QPushButton("Print", self) # Create options button self._options = QtGui.QToolButton(self) self._options.setIcon(pyzo.icons.wrench) self._options.setIconSize(QtCore.QSize(16, 16)) self._options.setPopupMode(self._options.InstantPopup) self._options.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) # Create options menu self._options._menu = QtGui.QMenu() self._options.setMenu(self._options._menu) # Create browser self._browser = QtGui.QTextBrowser(self) self._browser_text = initText # Create two sizers self._sizer1 = QtGui.QVBoxLayout(self) self._sizer2 = QtGui.QHBoxLayout() # Put the elements together self._sizer2.addWidget(self._text, 4) self._sizer2.addWidget(self._printBut, 0) self._sizer2.addWidget(self._options, 2) # self._sizer1.addLayout(self._sizer2, 0) self._sizer1.addWidget(self._browser, 1) # self._sizer1.setSpacing(2) self._sizer1.setContentsMargins(4, 4, 4, 4) self.setLayout(self._sizer1) # Set config toolId = self.__class__.__name__.lower() self._config = config = pyzo.config.tools[toolId] # if not hasattr(config, 'smartNewlines'): config.smartNewlines = True if not hasattr(config, 'fontSize'): if sys.platform == 'darwin': config.fontSize = 12 else: config.fontSize = 10 # Create callbacks self._text.returnPressed.connect(self.queryDoc) self._printBut.clicked.connect(self.printDoc) # self._options.pressed.connect(self.onOptionsPress) self._options._menu.triggered.connect(self.onOptionMenuTiggered) # Start self.setText() # Set default text self.onOptionsPress() # Fill menu
def updateItems(self): """ updateItems() Update the appearance of the items. """ # Get items and tab bar items = self.items() tabBar = self.tabBar() for i in range(len(items)): # Get item item = items[i] if item is None: continue # Update name and tooltip if item.dirty: #tabBar.setTabText(i, '*'+item.name) tabBar.setTabToolTip(i, item.filename + ' [modified]') else: tabBar.setTabText(i, item.name) tabBar.setTabToolTip(i, item.filename) # Determine text color. Is main file? Is current? if self._mainFile == item.id: tabBar.setTabTextColor(i, QtGui.QColor('#008')) elif i == self.currentIndex(): tabBar.setTabTextColor(i, QtGui.QColor('#000')) else: tabBar.setTabTextColor(i, QtGui.QColor('#444')) # Get number of blocks nBlocks = item.editor.blockCount() if nBlocks == 1 and not item.editor.toPlainText(): nBlocks = 0 # Update appearance of icon but = tabBar.tabButton(i, QtGui.QTabBar.LeftSide) but.updateIcon(item.dirty, self._mainFile == item.id, item.pinned, nBlocks)
def openColorDialog(self): """A simple function that opens a QColorDialog and link the dialog current color selection to the QLineEdit text """ dlg = QtWidgets.QColorDialog(self) dlg.setWindowTitle("Pick a color for the " + self.name.lower()) dlg.setCurrentColor(QtGui.QColor(self.text())) dlg.currentColorChanged.connect(lambda clr: self.setText(clr.name())) dlg.setModal(False) dlg.exec_()
def __init__(self, parent): # Create sub-widget self._edit = QtGui.QTextEdit(parent) self._edit.zoomOut(1) self._edit.setMaximumHeight(80) self._edit.setMinimumWidth(200) self._edit.textChanged.connect(self.onEditChanged) # Instantiate ShellinfoWithSystemDefault.__init__(self, parent, self._edit)
def __init__(self, parent): QtGui.QWidget.__init__(self, parent) # create toolbar self._toolbar = QtGui.QToolBar(self) self._toolbar.setMaximumHeight(25) self._toolbar.setIconSize(QtCore.QSize(16, 16)) # create stack self._stack = QtGui.QStackedWidget(self) # Populate toolbar self._shellButton = ShellControl(self._toolbar, self._stack) self._debugmode = 0 self._dbs = DebugStack(self._toolbar) # self._toolbar.addWidget(self._shellButton) self._toolbar.addSeparator() # self._toolbar.addWidget(self._dbc) -> delayed, see addContextMenu() self._condahelp = CondaHelper(self) # widget layout layout = QtGui.QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._toolbar) layout.addWidget(self._stack, 0) layout.addWidget(self._condahelp, 0) self.setLayout(layout) # make callbacks self._stack.currentChanged.connect(self.onCurrentChanged) # Make shared history (shared among shells) if PythonHistory is None: self.sharedHistory = None else: self.sharedHistory = PythonHistory('shellhistory.py') self.showCondaHelper()
def _getPixmap(self, icon): # Get icon if given by name if isinstance(icon, str): icon = pyzo.icons[icon] # Create pixmap if icon is None: pm = QtGui.QPixmap(16, 16) pm.fill(QtGui.QColor(0, 0, 0, 0)) return pm elif isinstance(icon, tuple): pm = QtGui.QPixmap(icon[0], icon[1]) pm.fill(QtGui.QColor(0, 0, 0, 0)) return pm elif isinstance(icon, QtGui.QPixmap): return icon elif isinstance(icon, QtGui.QIcon): return icon.pixmap(16, 16) else: raise ValueError( 'Icon for IconArtis should be icon, pixmap or name.')
def saveFile(self, editor=None, filename=None): """ Save the file. returns: True if succesfull, False if fails """ # get editor if editor is None: editor = self.getCurrentEditor() elif isinstance(editor, int): index = editor editor = None if index >= 0: item = self._tabs.items()[index] editor = item.editor if editor is None: return False # get filename if filename is None: filename = editor._filename if not filename: return self.saveFileAs(editor) # let the editor do the low level stuff... try: editor.save(filename) except Exception as err: # Notify in logger print("Error saving file:", err) # Make sure the user knows m = QtGui.QMessageBox(self) m.setWindowTitle("Error saving file") m.setText(str(err)) m.setIcon(m.Warning) m.exec_() # Return now return False # get actual normalized filename filename = editor._filename # notify # TODO: message concerining line endings print("saved file: {} ({})".format(filename, editor.lineEndingsHumanReadable)) self._tabs.updateItems() # todo: this is where we once detected whether the file being saved was a style file. # Notify done return True
def loadTool(self, toolId, splitWith=None): """ Load a tool by creating a dock widget containing the tool widget. """ # A tool id should always be lower case toolId = toolId.lower() # Close old one if toolId in self._activeTools: old = self._activeTools[toolId].widget() self._activeTools[toolId].setWidget(QtGui.QWidget(pyzo.main)) if old: old.close() old.deleteLater() # Get tool class (returns None on failure) toolClass = self.getToolClass(toolId) if toolClass is None: return # Already loaded? reload! if toolId in self._activeTools: self._activeTools[toolId].reload(toolClass) return # Obtain name from buffered list of names for toolDes in self._toolInfo: if toolDes.id == toolId: name = toolDes.name break else: name = toolId # Make sure there is a config entry for this tool if not hasattr(pyzo.config.tools, toolId): pyzo.config.tools[toolId] = ssdf.new() # Create dock widget and add in the main window dock = ToolDockWidget(pyzo.main, self) dock.setTool(toolId, name, toolClass) if splitWith and splitWith in self._activeTools: otherDock = self._activeTools[splitWith] pyzo.main.splitDockWidget(otherDock, dock, QtCore.Qt.Horizontal) else: pyzo.main.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock) # Add to list self._activeTools[toolId] = dock self.updateToolInstances()
def loadFile(self, filename, updateTabs=True): """ Load the specified file. On success returns the item of the file, also if it was already open.""" # Note that by giving the name of a tempfile, we can select that # temp file. # normalize path if filename[0] != '<': filename = normalizePath(filename) if not filename: return None # if the file is already open... for item in self._tabs.items(): if item.id == filename: # id gets _filename or _name for temp files break else: item = None if item: self._tabs.setCurrentItem(item) print("File already open: '{}'".format(filename)) return item # create editor try: editor = createEditor(self, filename) except Exception as err: # Notify in logger print("Error loading file: ", err) # Make sure the user knows m = QtGui.QMessageBox(self) m.setWindowTitle("Error loading file") m.setText(str(err)) m.setIcon(m.Warning) m.exec_() return None # create list item item = FileItem(editor) self._tabs.addItem(item, updateTabs) if updateTabs: self._tabs.setCurrentItem(item) # store the path self._lastpath = os.path.dirname(item.filename) return item
def onFontHelpOptionMenuTiggered(self, action): """ The user decides about font size in the Help. """ # Get text text = action.text().lower() if "size" in text: # Get font size size = int(text.split(":", 1)[1][:-2]) # Update self._config.fontSizeHelp = size # Set font size font = self._description.font() font.setPointSize(self._config.fontSizeHelp) self._description.setFont(QtGui.QFont(font))
def addTab(self, title, text, rich=True): # Create label to show info label = QtGui.QTextEdit(self) label.setLineWrapMode(label.WidgetWidth) label.setReadOnly(True) # Set text if rich: label.setHtml(text) else: label.setText(text) # Add to tab bar self._tabs.addTab(label, title) # Done return label
def __init__(self, parent): QtGui.QWidget.__init__(self, parent) # Get config toolId = self.__class__.__name__.lower( ) + '2' # This is v2 of the file browser if toolId not in pyzo.config.tools: pyzo.config.tools[toolId] = ssdf.new() self.config = pyzo.config.tools[toolId] # Ensure three main attributes in config for name in ['expandedDirs', 'starredDirs']: if name not in self.config: self.config[name] = [] # Ensure path in config if 'path' not in self.config or not isdir(self.config.path): self.config.path = op.expanduser('~') # Check expandedDirs and starredDirs. # Make path objects and remove invalid dirs. Also normalize case, # should not be necessary, but maybe the config was manually edited. expandedDirs, starredDirs = [], [] for d in self.config.starredDirs: if 'path' in d and 'name' in d and 'addToPythonpath' in d: if isdir(d.path): d.path = op.normcase(cleanpath(d.path)) starredDirs.append(d) for p in set([str(p) for p in self.config.expandedDirs]): if isdir(p): p = op.normcase(cleanpath(p)) # Add if it is a subdir of a starred dir for d in starredDirs: if p.startswith(d.path): expandedDirs.append(p) break self.config.expandedDirs, self.config.starredDirs = expandedDirs, starredDirs # Create browser(s). self._browsers = [] for i in [0]: self._browsers.append(Browser(self, self.config)) # Layout layout = QtGui.QVBoxLayout(self) self.setLayout(layout) layout.addWidget(self._browsers[0]) layout.setSpacing(0) layout.setContentsMargins(4, 4, 4, 4)