Exemplo n.º 1
0
class collectDelegate(QItemDelegate):

    def __init__(self, parent, module):
        self.module = module
        QItemDelegate.__init__(self, parent)

    def createEditor (self, parent, option, index):
        column = index.column()
        row = index.row()
        self.index = index
        content = index.model().data(index, Qt.EditRole)
        if column == 2:
            content = index.model().data(index, Qt.EditRole)
            label = index.model().data(index.model().index(row,1), Qt.EditRole)
            checkrowIndex = index.model().index(row,0)
            checkrowIndex = index.model().data(index.model().index(row,0), Qt.CheckStateRole)
            self.editorQWidget = QComboBox(parent)
            self.editorQWidget.setEditable(True)
            self.editorQWidget.addItems(self.module.fieldMapping.values())
            self.editorQWidget.addItems(['GEOMETRY','ODKUUID'])
            if content in self.module.fieldMapping.values():
                self.editorQWidget.setCurrentIndex(self.editorQWidget.findData(content))
                #self.module.fieldTable.item(row,0).setCheckState(Qt.Checked)
            else:
                #self.editorQWidget.insertItem(0,label)
                self.editorQWidget.insertItem(0,'')
                #self.module.fieldTable.item(row,0).setCheckState(Qt.Unchecked)
                self.editorQWidget.setCurrentIndex(0)
            return self.editorQWidget
        else:
            return None
        return QItemDelegate.createEditor(self, parent, option, index)
Exemplo n.º 2
0
    def createEditor(self, parent, option, index):
        """
        Creates the combobox inside a parent.
        :param parent: The container of the combobox
        :type parent: QWidget
        :param option: QStyleOptionViewItem class is used to describe the
        parameters used to draw an item in a view widget.
        :type option: Object
        :param index: The index where the combobox
         will be added.
        :type index: QModelIndex
        :return: The combobox
        :rtype: QComboBox
        """

        if index.column() == 0:
            str_combo = QComboBox(parent)
            str_combo.insertItem(0, " ")
            for id, type in self.str_type_set_data().iteritems():
                str_combo.addItem(type, id)
            if self.str_type_id is not None:
                str_combo.setCurrentIndex(self.str_type_id)
            return str_combo
        elif index.column() == 1:

            spinbox = QDoubleSpinBox(parent)
            spinbox.setObjectName(unicode(index.row()))
            spinbox.setMinimum(0.00)
            spinbox.setSuffix('%')
            spinbox.setMaximum(100.00)
            return spinbox
Exemplo n.º 3
0
 def createEditor(self, parent, option, index):
     editor = QComboBox(parent)
     i = 0
     for c in self.typeCaptions:
         editor.insertItem(i, c)
         i += 1
     return editor
Exemplo n.º 4
0
class LateralPanel(QWidget):

    def __init__(self, parent=None):
        super(LateralPanel, self).__init__(parent)
        self.has_component = False
        self.vbox = QVBoxLayout(self)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(self.combo, self.combo.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(self.trUtf8("Select the item from the Paste "
            "History list.\nYou can Copy items into this list with: "
            "%s\nor Paste them using: %s") %
                (resources.get_shortcut("History-Copy").toString(
                    QKeySequence.NativeText),
                resources.get_shortcut("History-Paste").toString(
                    QKeySequence.NativeText)))
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        self.vbox.addLayout(hbox)

    def add_component(self, widget):
        self.vbox.insertWidget(0, widget)
        self.has_component = True

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return self.combo.currentText()
Exemplo n.º 5
0
class ComboTabWidget(QWidget):
    def __init__(self, parent):
        super(ComboTabWidget, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        
        self.switchCombo = QComboBox(self)
        layout.addWidget(self.switchCombo, 0, Qt.AlignCenter)
        
        groupBox = QGroupBox(self)
        groupBoxLayout = QVBoxLayout(groupBox)
        groupBoxLayout.setSpacing(0)
        
        self.pageArea = QStackedWidget(groupBox)
        groupBoxLayout.addWidget(self.pageArea)
        
        layout.addWidget(groupBox, 1)
        
        self.switchCombo.currentIndexChanged.connect(self.pageArea.setCurrentIndex)
        
    def setTabPosition(self, tabPos):
        pass
        
    def addTab(self, w, tabText):
        self.pageArea.addWidget(w)
        self.switchCombo.addItem(tabText)
    
    def insertTab(self, pos, w, tabText):
        self.pageArea.insertWidget(pos, w)
        self.switchCombo.insertItem(pos, tabText)
        
    def removeTab(self, index=-1):
        if index < 0:
            index = self.currentIndex()
        
        w = self.pageArea.widget(index)
        
        self.pageArea.removeWidget(w)
        self.switchCombo.removeItem(index)
        
    def updateTab(self, w, tabText, index=-1):
        if index < 0:
            index = self.switchCombo.currentIndex()
        
        self.removeTab(index)
        self.insertTab(index, w, tabText)
        self.setCurrentIndex(index)
        
    def setCurrentIndex(self, index):
        self.switchCombo.setCurrentIndex(index)
        
    def widget(self, index):
        return self.pageArea.widget(index)
        
    def currentIndex(self):
        return self.switchCombo.currentIndex()
    
    def count(self):
        return self.switchCombo.count()
Exemplo n.º 6
0
 def createEditor(self,parent,option,index):
     """create widgets to edit values"""
     if index.column() == 1:
         cbox = QComboBox(parent)
         cbox.setMaxVisibleItems(10)            
         self.updateEditorGeometry(cbox, option,index )
         for pos,value in enumerate([0,20,30,40,50,60,70,80,90,100]):
             icon = QPixmap(20,10)
             icon.fill(self._getColorForProgress(value))
             cbox.insertItem(pos, QIcon(icon),"",value)
         cbox.showPopup()
         return cbox
     else:
         return QItemDelegate.createEditor(self,parent,option,index)
Exemplo n.º 7
0
class LateralPanel(QWidget):
    def __init__(self, parent=None):
        super(LateralPanel, self).__init__(parent)
        self.has_component = False
        self.vbox = QVBoxLayout(self)
        self.vbox.setContentsMargins(0, 0, 0, 0)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.labelText = "Ln: %s, Col: %s"
        self.labelCursorPosition = QLabel(self.trUtf8(self.labelText % (0, 0)))
        hbox.addWidget(self.labelCursorPosition)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(
            self.combo, self.combo.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(
            self.trUtf8(
                "Select the item from the Paste "
                "Historial list.\nYou can Copy items into this list with: "
                "%s\nor Paste them using: %s") %
            (resources.get_shortcut("History-Copy").toString(
                QKeySequence.NativeText),
             resources.get_shortcut("History-Paste").toString(
                 QKeySequence.NativeText)))
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        self.vbox.addLayout(hbox)

    def add_component(self, widget):
        self.vbox.insertWidget(0, widget)
        self.has_component = True

    def update_line_col(self, line, col):
        self.labelCursorPosition.setText(
            self.trUtf8(self.labelText % (line, col)))

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return self.combo.currentText()
Exemplo n.º 8
0
class LateralPanel(QWidget):
    def __init__(self, explorer):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.addWidget(explorer)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.labelText = "Ln: %1, Col: %2"
        self.labelCursorPosition = QLabel(
            self.tr(self.labelText).arg(0).arg(0))
        hbox.addWidget(self.labelCursorPosition)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(
            self.combo, self.combo.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(
            self.tr(
                "Select the item from the Paste "
                "Historial list.\nYou can Copy items into this list with: "
                "%1\nor Paste them using: %2").arg(
                    resources.get_shortcut("History-Copy").toString(
                        QKeySequence.NativeText)).arg(
                            resources.get_shortcut("History-Paste").toString(
                                QKeySequence.NativeText)))
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        vbox.addLayout(hbox)

    def update_line_col(self, line, col):
        self.labelCursorPosition.setText(
            self.tr(self.labelText).arg(line).arg(col))

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return unicode(self.combo.currentText())
Exemplo n.º 9
0
class LateralPanel(QWidget):
    def __init__(self, explorer):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.addWidget(explorer)
        hbox = QHBoxLayout()
        hbox.setContentsMargins(0, 0, 0, 0)
        self.labelText = "Ln: %s, Col: %s"
        self.labelCursorPosition = QLabel(self.trUtf8(self.labelText % (0, 0)))
        hbox.addWidget(self.labelCursorPosition)
        self.combo = QComboBox()
        ui_tools.ComboBoxButton(self.combo, self.combo.clear, self.style().standardPixmap(self.style().SP_TrashIcon))
        self.combo.setToolTip(
            self.trUtf8(
                "Select the item from the Paste "
                "Historial list.\nYou can Copy items into this list with: "
                "%s\nor Paste them using: %s"
                % (
                    resources.get_shortcut("History-Copy").toString(QKeySequence.NativeText),
                    resources.get_shortcut("History-Paste").toString(QKeySequence.NativeText),
                )
            )
        )
        self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        hbox.addWidget(self.combo)
        vbox.addLayout(hbox)

    def update_line_col(self, line, col):
        self.labelCursorPosition.setText(self.trUtf8(self.labelText % (line, col)))

    def add_new_copy(self, copy):
        self.combo.insertItem(0, copy)
        self.combo.setCurrentIndex(0)
        if self.combo.count() > settings.COPY_HISTORY_BUFFER:
            self.combo.removeItem(self.combo.count() - 1)

    def get_paste(self):
        return self.combo.currentText()
Exemplo n.º 10
0
class collectDelegate(QItemDelegate):
    def __init__(self, parent, module):
        self.module = module
        QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        column = index.column()
        self.index = index
        content = index.model().data(index, Qt.EditRole)
        if column == 2:
            self.content = index.model().data(index, Qt.EditRole)
            self.editorQWidget = QComboBox(parent)
            self.editorQWidget.setEditable(True)
            self.editorQWidget.addItems(self.module.fieldMapping.values())
            if self.content in self.module.fieldMapping.values():
                self.editorQWidget.setCurrentIndex(
                    self.editorQWidget.findData(self.content))
            else:
                self.editorQWidget.insertItem(0, '')
                self.editorQWidget.setCurrentIndex(0)
            return self.editorQWidget
        else:
            return None
            return QItemDelegate.createEditor(self, parent, option, index)
Exemplo n.º 11
0
class FindInFilesDialog(QDialog):
    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
                                       self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(
            self, self.tr("Open Directory"), self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Exemplo n.º 12
0
class SchemeSelector(QWidget):

    currentChanged = pyqtSignal()
    changed = pyqtSignal()

    def __init__(self, parent=None):
        super(SchemeSelector, self).__init__(parent)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.label = QLabel()
        self.scheme = QComboBox()
        self.menuButton = QPushButton(flat=True)
        menu = QMenu(self.menuButton)
        self.menuButton.setMenu(menu)
        layout.addWidget(self.label)
        layout.addWidget(self.scheme)
        layout.addWidget(self.menuButton)
        layout.addStretch(1)

        # action generator
        def act(slot, icon=None):
            a = QAction(self, triggered=slot)
            self.addAction(a)
            icon and a.setIcon(icons.get(icon))
            return a

        # add action
        a = self.addAction_ = act(self.slotAdd, 'list-add')
        menu.addAction(a)

        # remove action
        a = self.removeAction = act(self.slotRemove, 'list-remove')
        menu.addAction(a)

        # rename action
        a = self.renameAction = act(self.slotRename, 'document-edit')
        menu.addAction(a)

        menu.addSeparator()

        # import action
        a = self.importAction = act(self.slotImport, 'document-open')
        menu.addAction(a)

        # export action
        a = self.exportAction = act(self.slotExport, 'document-save-as')
        menu.addAction(a)

        self.scheme.currentIndexChanged.connect(self.slotSchemeChanged)
        app.translateUI(self)

    def translateUI(self):
        self.label.setText(_("Scheme:"))
        self.menuButton.setText(_("&Menu"))
        self.addAction_.setText(_("&Add..."))
        self.removeAction.setText(_("&Remove"))
        self.renameAction.setText(_("Re&name..."))
        self.importAction.setText(_("&Import..."))
        self.exportAction.setText(_("&Export..."))

    def slotSchemeChanged(self, index):
        """Called when the Scheme combobox is changed by the user."""
        self.disableDefault(self.scheme.itemData(index) == 'default')
        self.currentChanged.emit()
        self.changed.emit()

    def disableDefault(self, val):
        self.removeAction.setDisabled(val)
        self.renameAction.setDisabled(val)

    def schemes(self):
        """Returns the list with internal names of currently available schemes."""
        return [self.scheme.itemData(i) for i in range(self.scheme.count())]

    def currentScheme(self):
        """Returns the internal name of the currently selected scheme"""
        return self.scheme.itemData(self.scheme.currentIndex())

    def insertSchemeItem(self, name, scheme):
        for i in range(1, self.scheme.count()):
            n = self.scheme.itemText(i)
            if n.lower() > name.lower():
                self.scheme.insertItem(i, name, scheme)
                break
        else:
            self.scheme.addItem(name, scheme)

    def addScheme(self, name):
        num, key = 1, 'user1'
        while key in self.schemes() or key in self._schemesToRemove:
            num += 1
            key = 'user{0}'.format(num)
        self.insertSchemeItem(name, key)
        self.scheme.setCurrentIndex(self.scheme.findData(key))
        return key

    def slotAdd(self):
        name, ok = QInputDialog.getText(
            self, app.caption(_("Add Scheme")),
            _("Please enter a name for the new scheme:"))
        if ok:
            self.addScheme(name)

    def slotRemove(self):
        index = self.scheme.currentIndex()
        scheme = self.scheme.itemData(index)
        if scheme == 'default':
            return  # default can not be removed

        self._schemesToRemove.add(scheme)
        self.scheme.removeItem(index)

    def slotRename(self):
        index = self.scheme.currentIndex()
        name = self.scheme.itemText(index)
        scheme = self.scheme.itemData(index)
        newName, ok = QInputDialog.getText(self,
                                           _("Rename"),
                                           _("New name:"),
                                           text=name)
        if ok:
            self.scheme.blockSignals(True)
            self.scheme.removeItem(index)
            self.insertSchemeItem(newName, scheme)
            self.scheme.setCurrentIndex(self.scheme.findData(scheme))
            self.scheme.blockSignals(False)
            self.changed.emit()

    def slotImport(self):
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"),
                                                  _("All Files"))
        caption = app.caption(_("dialog title", "Import color theme"))
        filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(),
                                               filetypes)
        if filename:
            self.parent().import_(filename)

    def slotExport(self):
        name = self.scheme.currentText()
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"),
                                                  _("All Files"))
        caption = app.caption(
            _("dialog title", "Export {name}").format(name=name))
        path = os.path.join(QDir.homePath(), name + '.xml')
        filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)
        if filename:
            if os.path.splitext(filename)[1] != '.xml':
                filename += '.xml'
            self.parent().export(name, filename)

    def loadSettings(self, currentKey, namesGroup):
        # don't mark schemes for removal anymore
        self._schemesToRemove = set()

        s = QSettings()
        cur = s.value(currentKey, "default", type(""))

        # load the names for the shortcut schemes
        s.beginGroup(namesGroup)
        block = self.scheme.blockSignals(True)
        self.scheme.clear()
        self.scheme.addItem(_("Default"), "default")
        lst = [(s.value(key, key, type("")), key) for key in s.childKeys()]
        for name, key in sorted(lst, key=lambda f: f[0].lower()):
            self.scheme.addItem(name, key)

        # find out index
        index = self.scheme.findData(cur)
        self.disableDefault(cur == 'default')
        self.scheme.setCurrentIndex(index)
        self.scheme.blockSignals(block)
        self.currentChanged.emit()

    def saveSettings(self, currentKey, namesGroup, removePrefix=None):
        # first save new scheme names
        s = QSettings()
        s.beginGroup(namesGroup)
        for i in range(self.scheme.count()):
            if self.scheme.itemData(i) != 'default':
                s.setValue(self.scheme.itemData(i), self.scheme.itemText(i))

        for scheme in self._schemesToRemove:
            s.remove(scheme)
        s.endGroup()
        if removePrefix:
            for scheme in self._schemesToRemove:
                s.remove("{0}/{1}".format(removePrefix, scheme))
        # then save current
        scheme = self.currentScheme()
        s.setValue(currentKey, scheme)
        # clean up
        self._schemesToRemove = set()
Exemplo n.º 13
0
class ComboBoxPanel(QWidget):
    def __init__(self, parent, editable=False, spacerItemMove=False):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("ComboBoxPanel" +
                           str(len(parent.findChildren(ComboBoxPanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.comboBox = QComboBox(self.frameBoxPanel)
        self.comboBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(self.objectName() + "_comboBox")
        self.comboBox.setMinimumWidth(70)
        # self.comboBox.setMaximumWidth(70)

        # self.hLayoutframeBoxPanel.addWidget(self.lineEdit)
        self.hLayoutframeBoxPanel.addWidget(self.comboBox)

        self.imageButton = QToolButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)
        if not spacerItemMove:
            spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                     QSizePolicy.Minimum)
            self.hLayoutBoxPanel.addItem(spacerItem)

        self.comboBox.currentIndexChanged.connect(self.comboBoxChanged)
        # self.comboBox.editTextChanged.connect(self.comboBoxEditTextChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.captionUnits = ""

        self.hasObject = False

        self.objectList = []
        if editable == True:
            self.lineEdit = QLineEdit(self.frameBoxPanel)
            self.lineEdit.setObjectName("lineEdit")
            self.hLayoutframeBoxPanel.insertWidget(1, self.lineEdit)
            self.comboBox.setLineEdit(self.lineEdit)
            self.lineEdit.returnPressed.connect(self.comboBoxEditTextChanged)

    def FindString(self, string):
        return self.comboBox.findText(string)

    def comboBoxEditTextChanged(self):
        self.comboBox.showPopup()

    def get_Count(self):
        return self.comboBox.count()

    Count = property(get_Count, None, None, None)

    def method_0(self):
        return self.comboBox.currentIndex(
        ) >= 0 and self.SelectedItem != None and self.SelectedItem != ""

    def method_3(self, string_0):
        return self.comboBox.findText(string_0)

    def method_11(self, string_0):
        if (self.IsEmpty):
            return "%s%s\t" % (string_0, self.Caption)
        return "%s%s\t%s %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def comboBoxChanged(self):
        self.emit(SIGNAL("Event_0"), self)

    def IndexOf(self, item):
        if isinstance(item, str) or isinstance(item, QString):
            return self.comboBox.findText(item)
        else:
            return self.comboBox.findText(item.ToString())

    def Contains(self, item):
        compStr = None
        if isinstance(item, str):
            compStr = item
        elif isinstance(item, float) or isinstance(item, int):
            compStr = str(item)
        else:
            compStr = item.ToString()
        for i in range(self.comboBox.count()):
            comboItemstr = self.comboBox.itemText(i)
            if compStr == comboItemstr:
                return True
        return False

    def Clear(self):
        self.comboBox.clear()
        self.objectList = []
        self.hasObject = False

    def Add(self, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.comboBox.addItem(item.ToString())
            self.objectList.append(item)
            self.hasObject = True
            return
        self.comboBox.addItem(item)
        self.hasObject = False

    def Insert(self, index, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.comboBox.insertItem(index, item.ToString())
            self.objectList.insert(index, item)
            self.hasObject = True
            return
        self.comboBox.insertItem(index, item)
        self.hasObject = False

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_3"), self)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if captionStr == "":
            self.captionLabel.setText("")
            self.LabelWidth = 0
            return
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(captionStr + "(" +
                                      QString(self.CaptionUnits) + ")" + ":")
        else:
            self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def set_ButtonVisible(self, bool):
        self.imageButton.setVisible(bool)

    ButtonVisible = property(None, set_ButtonVisible, None, None)

    # def get_Value(self):
    #     return self.comboBox.currentIndex()

    # def set_Value(self, value):
    #     try:
    #         self.comboBox.setCurrentIndex(value)
    #     except:
    #         self.textBox.setText("")
    # Value = property(get_Value, set_Value, None, None)

    def get_IsEmpty(self):
        return self.comboBox.currentText() == "" or self.comboBox.currentIndex(
        ) == -1

    IsEmpty = property(get_IsEmpty, None, None, None)

    def get_ReadOnly(self):
        return self.textBox.isReadOnly()

    # def set_ReadOnly(self, bool):
    #     self.comboBox.setR.setReadOnly(bool)
    # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.comboBox.setMinimumSize(QSize(width, 0))
        self.comboBox.setMaximumSize(QSize(width, 16777215))

    Width = property(None, set_Width, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)

    def get_SelectedIndex(self):
        return self.comboBox.currentIndex()

    def set_SelectedIndex(self, index):
        if self.comboBox.count() == 0:
            return
        if index > self.comboBox.count() - 1:
            self.comboBox.setCurrentIndex(0)
        else:
            self.comboBox.setCurrentIndex(index)

    SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None)

    def get_Value(self):
        return self.comboBox.currentIndex()

    def set_Value(self, valueStr):
        if self.comboBox.count() == 0:
            return
        if valueStr == None:
            self.SelectedIndex = -1
            return
        self.comboBox.setCurrentIndex(self.comboBox.findText(str(valueStr)))

    Value = property(get_Value, set_Value, None, None)

    def get_Items(self):
        # if self.hasObject:
        #     return self.objectList
        itemList = []
        if self.comboBox.count() > 0:
            for i in range(self.comboBox.count()):
                itemList.append(self.comboBox.itemText(i))
        return itemList

    def set_AddItems(self, strList):
        self.Clear()
        if len(strList) != 0 and (not isinstance(strList[0], str)
                                  and not isinstance(strList[0], QString)):
            for obj in strList:
                self.comboBox.addItem(obj.ToString())
                self.objectList.append(obj)
            self.hasObject = True
            return
        self.comboBox.addItems(strList)

    Items = property(get_Items, set_AddItems, None, None)

    def get_Enabled(self):
        return self.comboBox.isEnabled()

    def set_Enabled(self, bool):
        self.comboBox.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_Editable(self):
        return self.comboBox.isEditable()

    def set_Editable(self, bool):
        self.comboBox.setEditable(bool)

    Editable = property(get_Editable, set_Editable, None, None)

    def get_SelectedItem(self):
        if self.comboBox.count() == 0:
            return None
        if self.hasObject:
            return self.objectList[self.SelectedIndex]
        return self.comboBox.currentText()

    def set_SelectedItem(self, val):
        index = self.comboBox.findText(val)
        self.comboBox.setCurrentIndex(index)

    SelectedItem = property(get_SelectedItem, set_SelectedItem, None, None)
Exemplo n.º 14
0
class FindInFilesDialog(QDialog):

    """Dialog to configure and trigger the search in the files."""

    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"), translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(QCompleter(
            ["*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(
            translations.TR_TEXT_FOR_REPLACE + "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(self, translations.TR_OPEN,
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Exemplo n.º 15
0
class NetWidget(QWidget):
       
    def __init__(self,parent = None):
        super(NetWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px")#设置整体的字体大小
        
        
        self.auto = False
        self.pro = QProcess(self)
#         self.tipDlg = TipDialog()
#         self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作
        
            #初始化comBox控件,并且为其添加选项
        self.comBox = QComboBox()
        self.comBox.setFixedWidth(120)
        self.comBox.insertItem(0, self.tr("ping"))
        self.comBox.insertItem(1, self.tr("ifconfig"))
        self.comBox.insertItem(2, self.tr("display"))
        #self.comBox.insertItem(3, self.tr("traceroute"))
        self.comBox.insertItem(4, self.tr("top"))
        self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联
        """
        #初始话控件设置
        #lineEdit,固定长度
        #runButton,显示字符串,信号量
        #pingLabel,当前显示字符
        #textBrower
          """ 
        self.lineEdit = QLineEdit()
        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit.setFixedWidth(250)
        self.runButton = QPushButton(self.tr("Run"))
        self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
        self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked)
        self.pingLabel = QLabel()#初始话,之后在函数操作中会改变
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser = QTextBrowser()
        """
            #布局一上,横向布局
            #将comBox,lineEdit,runButton添加到布局中
            #设置前面空为20和后面空为280
            """
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.comBox)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        #hLayout1.addStretch()
        hLayout1.addSpacing(280)
        
            #布局二中,横向布局
            #将pingLabel添加到布局中,并且诶设置前面的空白为20
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.pingLabel)
        
            #布局三下
            #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textBrowser)
        hLayout3.addSpacing(60)
        
            #主题布局总,纵向布局
            #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(40)
        self.setLayout(mainLayout)
        
        
        self.thread = MyThread()
        self.connect(self.thread,SIGNAL("getoutput"),self.append)
        
        
    def append(self,actionType):
        self.textBrowser.clear()
        self.textBrowser.append(actionType)
        #cursor = QTextCursor()
        #self.runButton.setText(self.tr("Stop"))
        
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.Start)
        self.textBrowser.setTextCursor(cursor)
        #changeLabel = QLabel()
    
    def onActivated(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        """#comBox的相应函数,随着comBox中字符串的改变,分别控制pingLabel的显示,以及lineEdit和textBrower的显示清除和可用状态
            #如果comBox当前的字符串文字为ping
            #pingLabel的文字设置为"提示:请在文本框中输入要ping的目标地址,然后点击执行获取结果",保持当前大小
            #lineEdit中内容清除,设置为不可用
            #textBrower清空"""
        if(self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setDisabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为ifconfig
            #类上所说
        elif(self.comBox.currentText() == "ifconfig"):
            self.pingLabel.setText(self.tr("Tip:get the net information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为display
        elif(self.comBox.currentText() == "display"):
            self.pingLabel.setText(self.tr("Tip:get the resolution information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
        
        elif(self.comBox.currentText() == "top"):
    
            self.pingLabel.setText(self.tr("Tip:run tom command"))
            self.pingLabel.adjustSize()
            self.lineEdit.setEnabled(False)
            self.lineEdit.clear()
            self.textBrowser.clear()
            #按钮的响应函数
    def runButton_clicked(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        #self.pro = QProcess(self)#外部程序使用声明
        desktop = QApplication.desktop()#获得桌面
        self.textBrowser.clear()#清除
        cmdstr = QString()
        center = QString()
        goal = QString()
        #comBox当前text为ping
        if (self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            if (self.runButton.text() == self.tr("Run")) :
                center = self.lineEdit.text().trimmed()
                if not center:
                    InfoHintDialog(self.tr("please input the IP address")).exec_()
#                     self.tipDlg.setTip(self.tr("请输入ping地址!!!"))
#                     self.tipDlg.show()
#                     self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
                    self.runButton.setText(self.tr("Run"))
                else:
                    self.comBox.setDisabled(True)
                    self.pro = QProcess(self)
                    self.runButton.setText(self.tr("stop ping"))
                    cmdstr = "ping " +center
                    self.textBrowser.clear()
                    self.textBrowser.append(self.tr(" ping ")+center+self.tr(" result:"))
            else:
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
                self.pro.close()
        elif(self.comBox.currentText() == "ifconfig"):
            self.pro = QProcess(self)
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            cmdstr = "ifconfig"
#             #如果comBox当前为traceroute
#         elif(self.comBox.currentText() == "traceroute"):
#                 goal = self.lineEdit.text()
#                 if (self.runButton.text() == u"执行"):
#                     if( goal.isEmpty() or goal.isNull() ):
#                         InfoHintDialog(u'请输入tracer地址:').exec_()
# #                         self.tipDlg.setTip(self.tr("请输入tracer地址:"))
# #                         self.tipDlg.show()
# #                         self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
# #                         
#                         #QMessageBox.information(self,self.tr("错误"),self.tr("请输入traceroute的目标地址"))
#                         #return
#                     else:
#                         self.proc = QProcess(self)
#                         #self.textBrowser.clear()
#                         cmdstrc = "traceroute -n "+ goal
#                         self.proc.start(cmdstrc)
#                         self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR)
#                         self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR)
#                         if self.proc.waitForStarted(10) == True:
#                             self.comBox.setDisabled(True)
#                             self.runButton.setText(self.tr("停止执行"))
#                 else:
#                     self.runButton.setText(self.tr("执行"))
#                     self.comBox.setDisabled(False)
#                     self.proc.close()
#             #如果comBox当前为display
        elif (self.comBox.currentText() == "display"):
            self.pro = QProcess(self)
            cmdstr = "../lib/ccr_jytcapi display"
            self.textBrowser.clear()
            #如果当前命令cmdstr不为空,则
        elif (self.comBox.currentText() == "top"):
            if self.runButton.text() == self.tr("Run") :
                self.thread.start()
                self.comBox.setDisabled(True)
                self.runButton.setText(self.tr("stop top"))
            else:
                self.textBrowser.clear()
                self.thread.auto = False
                #self.thread.destroyed()
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
        if (cmdstr != ""):
                self.pro.start(cmdstr)#开启执行命令
                self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数
                self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数
            
            #读取控制台输出
    def read(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardOutput())
        self.textBrowser.append(res)#添加到text框
        #读取错误
    def readError(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardError())
        self.textBrowser.append(res)
    def readR(self):
        
        res = QString.fromLocal8Bit(self.proc.readAllStandardOutput())
        #self.textBrowser.clear()
        self.textBrowser.append(res)
        


    def readErrorR(self):

        res = QString.fromLocal8Bit(self.proc.readAllStandardError())
        self.textBrowser.append(res)
        
    def updateWindow(self):
        if self.pro.isOpen():
            self.pro.close()
            
        self.thread.auto = False
        self.comBox.setDisabled(False)
        self.comBox.setCurrentIndex(0)
        self.runButton.setText((self.tr("Run")))
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser.clear()
Exemplo n.º 16
0
class FindInFilesDialog(QDialog):

    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
            self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(self,
            self.tr("Open Directory"),
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Exemplo n.º 17
0
class SearchBox(QWidget):
    def __init__(self, parent = None):
        super(SearchBox, self).__init__(parent) 
        self.setFixedHeight(30)
        
        self.lineEdit = QLineEdit()                
        self.lineEdit.setFixedHeight(29)
        self.lineEdit.setToolTip("输入搜索关键词")
        self.lineEdit.setFocusPolicy(Qt.ClickFocus)
        
        self.searchButton = QToolButton()
        self.searchButton.setText("搜索")
        self.searchButton.setFixedHeight(30)
        self.searchButton.setToolTip("点击搜索")
        self.searchButton.setCursor(QCursor(Qt.PointingHandCursor))
        
        self.resetButton = QToolButton()
        self.resetButton.setIcon(QIcon(":/iconSources/icons/reset.png"))
        self.resetButton.setIconSize(QSize(24, 24))
        self.resetButton.setFixedSize(27, 27)
        self.resetButton.setToolTip("重置搜索")
        self.resetButton.setCursor(QCursor(Qt.PointingHandCursor))
        
        self.clearButton = QToolButton()
        self.searchComboBox = QComboBox()
        self.searchComboBox.setToolTip("选择搜索类型")
        musicIcon = QIcon(":/iconSources/icons/music.png")
        artistIcon = QIcon(":/iconSources/icons/artist.png")
        albumIcon = QIcon(":/iconSources/icons/album.png")       
        self.searchComboBox.setIconSize(QSize(20,20))
        self.searchComboBox.insertItem(0, musicIcon, "歌曲")
        self.searchComboBox.insertItem(1, artistIcon, "歌手")
        self.searchComboBox.insertItem(2, albumIcon, "专辑")
        self.searchComboBox.setFixedSize(78, 27)
        self.searchComboBox.setCursor(Qt.PointingHandCursor)
        
        searchIcon = QIcon(":/iconSources/icons/delete.png")
        self.clearButton.setFixedSize(27, 27)
        self.clearButton.setIcon(searchIcon)
        self.clearButton.setIconSize(QSize(18, 18))
        self.clearButton.setAutoRaise(True)
        self.clearButton.setToolTip("清空搜索栏")
        self.clearButton.setCursor(Qt.PointingHandCursor)
        self.clearButton.hide()
        
        searchLayout = QHBoxLayout()
        searchLayout.addWidget(self.searchComboBox)
        searchLayout.addStretch()
        searchLayout.addWidget(self.clearButton)
        searchLayout.setMargin(1)
        searchLayout.setSpacing(0)
        searchLayout.setContentsMargins(0, 0, 0, 0)
        self.lineEdit.setLayout(searchLayout)
        self.lineEdit.setTextMargins(self.searchComboBox.width(), 0, self.clearButton.width(), 0)
        
        mainLayout = QHBoxLayout(self)
        mainLayout.setMargin(0)
        mainLayout.setSpacing(1)
        mainLayout.addWidget(self.resetButton)
        mainLayout.addWidget(self.lineEdit)
        mainLayout.addWidget(self.searchButton)

        #self.connect(self.clearButton, SIGNAL("clicked()"), self.lineEdit.clear)
        self.clearButton.clicked.connect(self.lineEdit.clear)
        self.lineEdit.textChanged.connect(self.clrbutton_show)
        
    def clrbutton_show(self):
        if self.lineEdit.text():
            self.clearButton.show()
        else:
            self.clearButton.hide()
Exemplo n.º 18
0
class SchemeSelector(QWidget):
    
    currentChanged = pyqtSignal()
    changed = pyqtSignal()
    
    def __init__(self, parent=None):
        super(SchemeSelector, self).__init__(parent)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        
        self.label = QLabel()
        self.scheme = QComboBox()
        self.menuButton = QPushButton(flat=True)
        menu = QMenu(self.menuButton)
        self.menuButton.setMenu(menu)
        layout.addWidget(self.label)
        layout.addWidget(self.scheme)
        layout.addWidget(self.menuButton)
        layout.addStretch(1)
        # action generator
        def act(slot, icon=None):
            a = QAction(self, triggered=slot)
            self.addAction(a)
            icon and a.setIcon(icons.get(icon))
            return a
        
        # add action
        a = self.addAction_ = act(self.slotAdd, 'list-add')
        menu.addAction(a)
        
        # remove action
        a = self.removeAction = act(self.slotRemove, 'list-remove')
        menu.addAction(a)
        
       
        # rename action
        a = self.renameAction = act(self.slotRename, 'document-edit')
        menu.addAction(a)
        
        menu.addSeparator()
        
        # import action
        a = self.importAction = act(self.slotImport, 'document-open')
        menu.addAction(a)
        
        # export action
        a = self.exportAction = act(self.slotExport, 'document-save-as')
        menu.addAction(a)
        
        
        self.scheme.currentIndexChanged.connect(self.slotSchemeChanged)
        app.translateUI(self)
        
    def translateUI(self):
        self.label.setText(_("Scheme:"))
        self.menuButton.setText(_("&Menu"))
        self.addAction_.setText(_("&Add..."))
        self.removeAction.setText(_("&Remove"))
        self.renameAction.setText(_("Re&name..."))
        self.importAction.setText(_("&Import..."))
        self.exportAction.setText(_("&Export..."))
        
    def slotSchemeChanged(self, index):
        """Called when the Scheme combobox is changed by the user."""
        self.disableDefault(self.scheme.itemData(index) == 'default')
        self.currentChanged.emit()
        self.changed.emit()
    
    def disableDefault(self, val):
        self.removeAction.setDisabled(val)
        self.renameAction.setDisabled(val)
    
    def schemes(self):
        """Returns the list with internal names of currently available schemes."""
        return [self.scheme.itemData(i) for i in range(self.scheme.count())]
        
    def currentScheme(self):
        """Returns the internal name of the currently selected scheme"""
        return self.scheme.itemData(self.scheme.currentIndex())
        
    def insertSchemeItem(self, name, scheme):
        for i in range(1, self.scheme.count()):
            n = self.scheme.itemText(i)
            if n.lower() > name.lower():
                self.scheme.insertItem(i, name, scheme)
                break
        else:
            self.scheme.addItem(name, scheme)
    
    def addScheme(self, name):
        num, key = 1, 'user1'
        while key in self.schemes() or key in self._schemesToRemove:
            num += 1
            key = 'user{0}'.format(num)
        self.insertSchemeItem(name, key)
        self.scheme.setCurrentIndex(self.scheme.findData(key))
        return key
    
    def slotAdd(self):
        name, ok = QInputDialog.getText(self,
            app.caption(_("Add Scheme")),
            _("Please enter a name for the new scheme:"))
        if ok:
            self.addScheme(name)
        
    
    def slotRemove(self):
        index = self.scheme.currentIndex()
        scheme = self.scheme.itemData(index)
        if scheme == 'default':
            return # default can not be removed
        
        self._schemesToRemove.add(scheme)
        self.scheme.removeItem(index)
    
    def slotRename(self):
        index = self.scheme.currentIndex()
        name = self.scheme.itemText(index)
        scheme = self.scheme.itemData(index)
        newName, ok = QInputDialog.getText(self, _("Rename"), _("New name:"), text=name)
        if ok:
            self.scheme.blockSignals(True)
            self.scheme.removeItem(index)
            self.insertSchemeItem(newName, scheme)
            self.scheme.setCurrentIndex(self.scheme.findData(scheme))
            self.scheme.blockSignals(False)
            self.changed.emit()
           
    def slotImport(self):
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
        caption = app.caption(_("dialog title", "Import color theme"))
        filename = QFileDialog.getOpenFileName(self, caption, os.environ['HOME'], filetypes)
        if filename:
            self.parent().import_(filename)
    
    def slotExport(self):
        name = self.scheme.currentText()
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
        caption = app.caption(_("dialog title",
            "Export {name}").format(name=name))
        path = os.path.join(os.environ['HOME'], name+'.xml')
        filename = QFileDialog.getSaveFileName(self, caption, path, filetypes)
        if filename:
            if os.path.splitext(filename)[1] != '.xml':
                filename += '.xml'
            self.parent().export(name, filename)
            
    
    def loadSettings(self, currentKey, namesGroup):
        # dont mark schemes for removal anymore
        self._schemesToRemove = set()
        
        s = QSettings()
        cur = s.value(currentKey, "default", type(""))
        
        # load the names for the shortcut schemes
        s.beginGroup(namesGroup)
        self.scheme.clear()
        self.scheme.addItem(_("Default"), "default")
        lst = [(s.value(key, key, type("")), key) for key in s.childKeys()]
        for name, key in sorted(lst, key=lambda f: f[0].lower()):
            self.scheme.addItem(name, key)
        block = self.scheme.blockSignals(True)
        
        # find out index
        index = self.scheme.findData(cur)
        self.disableDefault(cur == 'default')
        self.scheme.setCurrentIndex(index)
        self.scheme.blockSignals(block)
        self.currentChanged.emit()
        
    def saveSettings(self, currentKey, namesGroup, removePrefix=None):
        # first save new scheme names
        s = QSettings()
        s.beginGroup(namesGroup)
        for i in range(self.scheme.count()):
            if self.scheme.itemData(i) != 'default':
                s.setValue(self.scheme.itemData(i), self.scheme.itemText(i))
        
        for scheme in self._schemesToRemove:
            s.remove(scheme)
        s.endGroup()
        if removePrefix:
            for scheme in self._schemesToRemove:
                s.remove("{0}/{1}".format(removePrefix, scheme))
        # then save current
        scheme = self.currentScheme()
        s.setValue(currentKey, scheme)
        # clean up
        self._schemesToRemove = set()
Exemplo n.º 19
0
class FindInFilesDialog(QDialog):
    """Dialog to configure and trigger the search in the files."""
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(
            self, translations.TR_OPEN, self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
Exemplo n.º 20
0
class dbsMiscControlsDialog(QDialog):
    def __init__(self, callback, parent=None):
        QDialog.__init__(self, parent)
        self.callback = callback
        self.create_widgets()
        self.layout_widgets()
        self.create_connections()
        self.setModal(False)
        self.setWindowTitle('Misc. Controls')
        
    def create_widgets(self):        
        self.op_pick_label = QLabel('Picking Opacity Isoval')
        self.op_pick_sbox = QDoubleSpinBox()
        self.op_pick_sbox.setRange(0, 1.0)
        self.op_pick_sbox.setSingleStep(0.02)
        self.op_pick_sbox.setValue(0.5)
        
        self.vta_combox_label = QLabel('Statistic')
        self.vta_stats_combox = QComboBox()
        self.vta_stats_combox.insertItem(0, 'Mean')
        self.vta_stats_combox.insertItem(1, 'Var')
        self.vta_stats_combox.insertItem(2, 'Min')
        self.vta_stats_combox.insertItem(3, 'Max')
        self.vta_stats_combox.insertItem(4, 'Mean-Var')
        self.vta_stats_combox.insertItem(5, 'Min-Var')
        self.vta_stats_combox.insertItem(6, 'Max-Var')
        self.vta_stats_combox.insertItem(7, 'NumSamples')
        
        self.__setupWidgetsForClippingPlanes()
        
    def layout_widgets(self):
        misc_controls_gl = QGridLayout()
        
        misc_controls_gl.addWidget(self.vta_combox_label, 0, 0)
        misc_controls_gl.addWidget(self.vta_stats_combox, 0, 1)
        
        misc_controls_gl.addWidget(self.op_pick_label, 1, 0)
        misc_controls_gl.addWidget(self.op_pick_sbox, 1, 1)
        
        misc_controls_gl.addWidget(self.cpl_xmax_label, 2, 0)
        misc_controls_gl.addWidget(self.cpl_xmax, 2, 1)
        misc_controls_gl.addWidget(self.cpl_ymax_label, 3, 0)
        misc_controls_gl.addWidget(self.cpl_ymax, 3, 1)
        misc_controls_gl.addWidget(self.cpl_zmax_label, 4, 0)
        misc_controls_gl.addWidget(self.cpl_zmax, 4, 1)
        
        self.setLayout(misc_controls_gl)
        self.layout().setSizeConstraint( QLayout.SetFixedSize )


    def create_connections(self):
        self.op_pick_sbox.valueChanged.connect(self.__setVolOpacityForPicking)
        self.cpl_ymax.valueChanged.connect(self.__setClippingPlaneYmax)
        self.cpl_xmax.valueChanged.connect(self.__setClippingPlaneXmax)
        self.cpl_zmax.valueChanged.connect(self.__setClippingPlaneZmax)
        self.vta_stats_combox.currentIndexChanged.connect(self.__setVolToRender)
        
    def getStatComboBoxIndex(self, stat):
        ''' Returns index of statistic. '''
        
        if stat == 'Mean':
            return 0
        elif stat == 'Var':
            return 1
        elif stat == 'Min':
            return 2
        elif stat == 'Max':
            return 3
        elif stat == 'Mean-Var':
            return 4
        elif stat == 'Min-Var':
            return 5
        elif stat == 'Max-Var':
            return 6
        elif stat == 'NumSamples':
            return 6
        
        
    def updateWidgetValues(self):
        ''' Allows application to set values on widget controls. '''
        
        par = self.parent()
        actv = self.parent().active_vol
        
        self.cpl_xmax.setValue(par._vdata[actv].volumeClipXmax.GetOrigin()[0])
        self.cpl_ymax.setValue(par._vdata[actv].volumeClipYmax.GetOrigin()[1])
        self.cpl_zmax.setValue(par._vdata[actv].volumeClipXmax.GetOrigin()[2])
        
        self.op_pick_sbox.setValue(par._vdata[actv].picking_opacity)
        
        stat = QString(par._vdata[actv].curr_statistic)
        idx = self.getStatComboBoxIndex(stat)
        self.vta_stats_combox.setCurrentIndex(idx)
        
        
    def __setupWidgetsForClippingPlanes(self): 
        self.cpl_xmax_label = QLabel( 'Clipping Plane X' )
        self.cpl_xmax = QSlider(Qt.Horizontal)
        self.cpl_xmax.setRange(-30.000000, -30 + 120 * 0.252) # data set dependent
        # todo - set this with loadable dimensions config file with data

        self.cpl_ymax_label = QLabel( 'Clipping Plane Y' )
        self.cpl_ymax = QSlider(Qt.Horizontal)
        self.cpl_ymax.setRange(-15.000000, -15 + 120 * 0.252)
        
        self.cpl_zmax_label = QLabel( 'Clipping Plane Z' )
        self.cpl_zmax = QSlider(Qt.Horizontal)
        self.cpl_zmax.setRange(-30.000000, -30 + 120 * 0.252)
        
        
    def __setVolOpacityForPicking(self):
        op = self.op_pick_sbox.value()
        av = self.parent().active_vol
        self.parent()._vdata[av].picking_opacity = op
        self.parent()._picker.SetVolumeOpacityIsovalue(op)


    def __setClippingPlaneYmax(self):
        av = self.parent().active_vol
        self.parent()._vdata[av].yclip = self.cpl_ymax.value() 
        self.parent()._vdata[av].volumeClipYmax.SetOrigin(-30, self.cpl_ymax.value(), -30)        
        self.apply()
        
    def __setClippingPlaneXmax(self):
        av = self.parent().active_vol
        self.parent()._vdata[av].xclip = self.cpl_xmax.value()
        self.parent()._vdata[av].volumeClipXmax.SetOrigin(self.cpl_xmax.value(), -10, -30)
        self.apply()
    
    
    def __setClippingPlaneZmax(self):
        av = self.parent().active_vol
        self.parent()._vdata[av].zclip = self.cpl_zmax.value()
        self.parent()._vdata[av].volumeClipZmax.SetOrigin(-30, -10, self.cpl_zmax.value())
        self.apply()
        
        
    def __setVolToRender(self):
        par = self.parent()
        stat = self.vta_stats_combox.currentText()
        av = par.active_vol 
        
        vol_to_renderer = str(stat)
        par._vdata[av].curr_statistic = vol_to_renderer
        par._vdata[av].assignVolumeProperties()        
        par._colorControlsDialog.setTFChart( par._vdata[av].chart )
        
        self.__setClippingPlaneXmax()
        self.__setClippingPlaneYmax()
        self.__setClippingPlaneZmax()
        
        self.apply()


    def apply(self):
        av = self.parent().active_vol
        self.parent().vol_qvtk_widgets[av].update()