示例#1
0
    def __init__(self, parent):
        QtWidgets.QWidget.__init__(self, parent)

        # create toolbar
        self._toolbar = QtWidgets.QToolBar(self)
        self._toolbar.setMaximumHeight(26)
        self._toolbar.setIconSize(QtCore.QSize(16, 16))

        # create stack
        self._stack = QtWidgets.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._interpreterhelp = InterpreterHelper(self)

        # widget layout
        layout = QtWidgets.QVBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._toolbar)
        layout.addWidget(self._stack, 0)
        layout.addWidget(self._interpreterhelp, 0)
        self.setLayout(layout)

        # make callbacks
        self._stack.currentChanged.connect(self.onCurrentChanged)

        self.showInterpreterHelper()
示例#2
0
    def __init__(self, parent, i):
        QtWidgets.QWizardPage.__init__(self, parent)
        self._i = i

        # Create label for description
        self._text_label = QtWidgets.QLabel(self)
        self._text_label.setTextFormat(QtCore.Qt.RichText)
        self._text_label.setWordWrap(True)

        # Create label for image
        self._comicLabel = QtWidgets.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 = QtWidgets.QVBoxLayout(self)
        self.setLayout(theLayout)
        #
        theLayout.addWidget(self._text_label)
        theLayout.addStretch()
        theLayout.addWidget(self._comicLabel)
        theLayout.addStretch()
示例#3
0
 def __init__(self, parent=None):
     QtWidgets.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 = QtWidgets.QLabel(text, self)
     self._no = QtWidgets.QPushButton("No thanks (dont ask again)")
     self._yes = QtWidgets.QPushButton("Yes, please install Python!")
     
     self._no.clicked.connect(self.reject)
     self._yes.clicked.connect(self.accept)
     
     vbox = QtWidgets.QVBoxLayout(self)
     hbox = QtWidgets.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)
示例#4
0
    def __init__(self, parent, distro=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setMinimumSize(360, 256)  # Ensure title fits nicely

        # Create label widget and costumize
        self._label = QtWidgets.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 = QtWidgets.QVBoxLayout(self)
        self.setLayout(layout)
        layout.addStretch(1)
        layout.addWidget(self._label, 0)
        layout.addStretch(1)
示例#5
0
    def __init__(self, name, other):
        super().__init__()
        self.widget = other
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(
            QtWidgets.QLabel(text=name.capitalize().strip() + " :"))
        layout.addWidget(other)

        self.setLayout(layout)
示例#6
0
 def __init__(self, parent = None):
     super().__init__(parent)
     
     # Widgets
     self._search = QtWidgets.QLineEdit(self)
     self._list = QtWidgets.QListWidget(self)
     
     # Set monospace
     font = self._list.font()
     font.setFamily(pyzo.config.view.fontname)
     self._list.setFont(font)
     
     # Layout
     layout = QtWidgets.QVBoxLayout(self)
     self.setLayout(layout)
     layout.addWidget(self._search, 0)
     layout.addWidget(self._list, 1)
     # set margins
     margin = pyzo.config.view.widgetMargin
     layout.setContentsMargins(margin, margin, margin, margin)
     
     # Customize line edit
     self._search.setPlaceholderText(translate('menu', 'Search'))
     self._search.textChanged.connect(self._on_search)
     
     # Drag/drop
     self._list.setSelectionMode(self._list.ExtendedSelection)
     self._list.setDragEnabled(True)
     self._list.doubleClicked.connect(self._onDoubleClicked)
     
     # Context menu
     self._menu = Menu(self, translate("menu", "History"))
     self._menu.addItem(translate("menu", "Copy ::: Copy selected lines"),
         pyzo.icons.page_white_copy, self.copy, "copy")
     self._menu.addItem(translate("menu", "Run ::: Run selected lines in current shell"),
         pyzo.icons.run_lines, self.runSelection, "run")
     self._menu.addItem(translate("menu", "Remove ::: Remove selected history items(s)"),
         pyzo.icons.delete, self.removeSelection, "remove")
     
     self._list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
     self._list.customContextMenuRequested.connect(self._onCustomContextMenuRequested)
     
     # Populate
     for command in pyzo.command_history.get_commands():
         self._list.addItem(command)
     
     # Scroll to end of list on start up
     self._list.setCurrentRow(self._list.count()-1)
     item = self._list.currentItem()
     self._list.scrollToItem(item)
     
     # Keep up to date ...
     pyzo.command_history.command_added.connect(self._on_command_added)
     pyzo.command_history.command_removed.connect(self._on_command_removed)
     pyzo.command_history.commands_reset.connect(self._on_commands_reset)
示例#7
0
    def __init__(self, parent=None):
        super().__init__(parent)

        # File encoding
        self.file_encoding = QtWidgets.QLabel(self)
        self.file_encoding.setFixedWidth(100)
        self.insertPermanentWidget(0, self.file_encoding, 0)

        # Cursor position
        self.cursor_pos = QtWidgets.QLabel(self)
        self.cursor_pos.setFixedWidth(190)
        self.insertPermanentWidget(1, self.cursor_pos, 0)
示例#8
0
    def __init__(self, parent):
        # Do not pass parent, because is a sublayout
        QtWidgets.QVBoxLayout.__init__(self)

        # Create sub-widget
        self._edit1 = QtWidgets.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 = QtWidgets.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 = QtWidgets.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 = QtWidgets.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 = QtWidgets.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'
示例#9
0
    def __init__(self, parent):
        super().__init__(parent)

        self._label = QtWidgets.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() + 2)
        self._label.setFont(font)

        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self._label, 1)
示例#10
0
    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 = QtWidgets.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()
示例#11
0
    def __init__(self, parent):
        QtWidgets.QTreeWidget.__init__(self, parent)

        self._config = parent._config

        # Set header stuff
        self.setHeaderHidden(False)
        self.setColumnCount(3)
        self.setHeaderLabels([
            pyzo.translate("pyzoWorkspace", 'Name'),
            pyzo.translate("pyzoWorkspace", 'Type'),
            pyzo.translate("pyzoWorkspace", '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 = QtWidgets.QMenu()
        self._menu.triggered.connect(self.contextMenuTriggered)

        # Bind to events
        self.itemActivated.connect(self.onItemExpand)

        self._startUpVariables = ["In", "Out", "exit", "get_ipython", "quit"]
示例#12
0
    def _export_pdf(self):
        """Exports the code as pdf, and opens file manager"""
        if self.editor is not None:

            from pyzo.util.qt import QtPrintSupport

            if True:
                filename = QtWidgets.QFileDialog.getSaveFileName(
                    None, 'Export PDF', os.path.expanduser("~"), "*.pdf *.ps")
                if isinstance(filename, tuple):  # PySide
                    filename = filename[0]
                if not filename:
                    return
                self.printer.setOutputFileName(filename)
            else:
                d = QtWidgets.QPrintDialog(printer)
                d.setWindowTitle('Print code')
                d.setOption(d.PrintSelection,
                            self.editor.textCursor().hasSelection())
                d.setOption(d.PrintToFile, True)
                ok = d.exec_()
                if ok != d.Accepted:
                    return

        try:
            self._print()
            self.editor.print_(self.printer)

        except print_error:
            print(print_error)
示例#13
0
 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))
示例#14
0
 def showMenu(self, pos):
     menu = self._browser.createStandardContextMenu()
     help = QtWidgets.QAction(
         pyzo.icons.help,
         pyzo.translate("pyzoInteractiveHelp", "Help on this"), menu)
     help.triggered.connect(partial(self.helpOnThis, pos=pos))
     menu.insertAction(menu.actions()[0], help)
     menu.exec(self.mapToGlobal(pos))
示例#15
0
    def __init__(self, parent):
        QtWidgets.QWidget.__init__(self, parent)

        # Create text field, checkbox, and button
        self._text = QtWidgets.QLineEdit(self)
        self._printBut = QtWidgets.QPushButton("Print", self)

        # Create options button
        self._options = QtWidgets.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 = QtWidgets.QMenu()
        self._options.setMenu(self._options._menu)

        # Create browser
        self._browser = QtWidgets.QTextBrowser(self)
        self._browser_text = initText

        # Create two sizers
        self._sizer1 = QtWidgets.QVBoxLayout(self)
        self._sizer2 = QtWidgets.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
示例#16
0
    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 = QtWidgets.QLabel(t1, self)
        #self._check_show = QtWidgets.QCheckBox(t2, self)
        #self._check_show.stateChanged.connect(self._setNewUser)

        # Create language switcher
        self._langLabel = QtWidgets.QLabel(
            translate('wizard', "Select language"), self)
        #
        self._langBox = QtWidgets.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 = QtWidgets.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)
示例#17
0
    def show_output(self):
        """ show_output()
        Fill the tree
        """

        num_c = 0
        num_r = 0
        num_w = 0
        num_e = 0
        num_a = 0

        # write output in the file
        output_file = os.path.join(self.output_folder, "pylinter_output.txt")
        with open(output_file, "w") as res:
            res.write(self.output)

        for line in self.output.splitlines():
            line = line.split(":")
            try:
                editor = pyzo.editors.getCurrentEditor()
                path = os.path.join(os.path.curdir, editor.filename)
                #path = l[-5].strip()
                line_num = line[-4].strip()
                col = line[-3].strip()
                msg_id = line[-2].strip()
                msg = line[-1].strip()

                QtWidgets.QTreeWidgetItem(self._tree,
                                          [msg, path, msg_id, line_num, col])

                if msg_id[0] == "C":
                    num_c += 1
                elif msg_id[0] == "R":
                    num_r += 1
                elif msg_id[0] == "W":
                    num_w += 1
                elif msg_id[0] == "E":
                    num_e += 1
                num_a = num_c + num_r + num_w + num_e
            except:
                if line[0].strip().startswith("Your code"):
                    res = line[0].replace("Your code has been rated at", "")
                    res = res.replace("(previous run", "")
                    try:
                        prevsplit = line[1].split(",")
                        prev = prevsplit[1].replace(")", "")
                        self._ratings.setText(res + prev)
                    except:
                        pass

        self._all.setText("{} ({})".format(ALL, str(num_a)))
        self._convention.setText("{} ({})".format(CONVENTION, str(num_c)))
        self._refactor.setText("{} ({})".format(REFACTOR, str(num_r)))
        self._warning.setText("{} ({})".format(WARNING, str(num_w)))
        self._error.setText("{} ({})".format(ERROR, str(num_e)))

        self.on_radio_change_state(self._convention)
示例#18
0
    def __init__(self, engine):
        super().__init__()
        self._engine = engine
        layout = QtWidgets.QVBoxLayout(self)
        add_button = QtWidgets.QPushButton("Add")
        del_button = QtWidgets.QPushButton("Delete")
        self._view = QtWidgets.QListView()
        layout.addWidget(self._view)
        layout2 = QtWidgets.QHBoxLayout()
        layout2.addWidget(add_button)
        layout2.addWidget(del_button)
        layout.addLayout(layout2)
        self._model = QtCore.QStringListModel()
        self._view.setModel(self._model)

        self._model.setStringList(self._engine.registeredDocumentations())

        add_button.clicked.connect(self.add_doc)
        del_button.clicked.connect(self.del_doc)
示例#19
0
 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_()
示例#20
0
    def __init__(self, parent):

        # Create sub-widget
        self._edit = QtWidgets.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)
示例#21
0
    def __init__(self, parent):
        QtWidgets.QWidget.__init__(self, parent)

        # create toolbar
        self._toolbar = QtWidgets.QToolBar(self)
        self._toolbar.setMaximumHeight(25)
        self._toolbar.setIconSize(QtCore.QSize(16, 16))

        # create stack
        self._stack = QtWidgets.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 = QtWidgets.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()
示例#22
0
    def __init__(self, parent, distro=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setMinimumSize(360, 256)  # Ensure title fits nicely

        # Create label widget and costumize
        self._label = QtWidgets.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
        text_title = translate(
            "splash",
            "This is <b>Pyzo</b><br />the Python IDE for scientific computing")
        text_version = translate("splash", "Version")
        text_os = translate(
            "splash",
            "Pyzo is open source software and freely available for everyone.")
        text = splash_text.format(
            version=pyzo.__version__,
            text_title=text_title,
            text_version=text_version,
            text_os=text_os,
        )

        # Set text
        self._label.setText(text)

        layout = QtWidgets.QVBoxLayout(self)
        self.setLayout(layout)
        layout.addStretch(1)
        layout.addWidget(self._label, 0)
        layout.addStretch(1)
示例#23
0
    def fillTree(self):
        # fill tree
        self._snippet = {}
        self._part = {}
        for f in os.listdir(self.snippet_folder):

            root = f.replace(".json", "").title()
            sf = os.path.join(self.snippet_folder, f)
            with open(sf) as snippet:
                self._part[root] = load(snippet)
                self._snippet.update(self._part)
                root = QtWidgets.QTreeWidgetItem(self._tree, [root])
                for k, v in self._part.items():
                    for kk, vv in v.items():

                        QtWidgets.QTreeWidgetItem(
                            root, [str(kk), str(vv["prefix"])])
                self._part.clear()
        self._tree.sortItems(0, QtCore.Qt.AscendingOrder)
        self._sort_order = "ASC"
        self._sortbut.setText("A-z")
        self._sortbut.setArrowType(QtCore.Qt.DownArrow)
示例#24
0
文件: __init__.py 项目: solversa/pyzo
    def __init__(self, parent):
        QtWidgets.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 = QtWidgets.QVBoxLayout(self)
        self.setLayout(layout)
        layout.addWidget(self._browsers[0])
        layout.setSpacing(0)
        # set margins
        margin = pyzo.config.view.widgetMargin
        layout.setContentsMargins(margin, margin, margin, margin)
示例#25
0
文件: editorTabs.py 项目: tjguk/pyzo
    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 = QtWidgets.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
示例#26
0
文件: editorTabs.py 项目: tjguk/pyzo
    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 = QtWidgets.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
示例#27
0
 def addTab(self, title, text, rich=True):
     # Create label to show info
     label = QtWidgets.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
示例#28
0
文件: __init__.py 项目: stonebig/pyzo
    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(QtWidgets.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()
示例#29
0
    def __add_checkBox(self, key, name):
        """this is a helper method to create a QCheckBox
            it adds the created widget (as a TitledWidget) to the layout and
            register a setter and listen to changes
        """

        checkBox = QtWidgets.QCheckBox()

        self.setters[key] = (
            lambda val, check=checkBox: check.setCheckState(val == "yes"))

        checkBox.stateChanged.connect(lambda state, key=key: self.__update(
            key, "yes" if state else "no"))

        self.layout.addWidget(TitledWidget(name, checkBox))
示例#30
0
    def __init__(self, name, *args, **kwargs):
        """The name is displayed in the QColorDialog"""
        super().__init__(*args, **kwargs)
        self.name = name
        self.button = QtWidgets.QToolButton(self)
        self.button.setIcon(QtGui.QIcon(pyzo.icons.cog))
        self.button.setStyleSheet('border: 0px; padding: 0px')
        self.button.clicked.connect(self.openColorDialog)

        frameWidth = self.style().pixelMetric(
            QtWidgets.QStyle.PM_DefaultFrameWidth)
        buttonSize = self.button.sizeHint()

        self.setStyleSheet('QLineEdit {padding-right: %dpx; }' %
                           (buttonSize.width() + frameWidth + 1))