コード例 #1
0
class NotebookExtSettingsDialog(QDialog):
    def __init__(self, parent=None, cfg_list=[]):
        super(NotebookExtSettingsDialog, self).__init__(parent)
        self.extCfgEdit = QTreeWidget()
        self.extCfgEdit.setHeaderLabels(['Property', 'Value'])
        self.addRow = QPushButton('+')
        self.removeRow = QPushButton('-')
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        layout = QGridLayout(self)
        layout.addWidget(self.extCfgEdit, 0, 0, 1, 2)
        layout.addWidget(self.addRow, 1, 0, 1, 1)
        layout.addWidget(self.removeRow, 1, 1, 1, 1)
        layout.addWidget(self.buttonBox, 2, 0, 1, 2)
        self.initCfgPanel(cfg_list)

        self.addRow.clicked.connect(self.actionAdd)
        self.removeRow.clicked.connect(self.actionRemove)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def initCfgPanel(self, cfg_list):
        for item in cfg_list:
            self.actionAdd(prop_name=item[0], prop_val=item[1])

    def actionRemove(self):
        item = self.extCfgEdit.currentItem()
        row = self.extCfgEdit.indexOfTopLevelItem(item)
        self.extCfgEdit.takeTopLevelItem(row)

    def actionAdd(self, checked=False, prop_name='', prop_val=''):
        item = QTreeWidgetItem(self.extCfgEdit, [prop_name, prop_val])
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        #self.extCfgEdit.addTopLevelItem(item)

    def configToList(self):
        items = []
        for i in range(self.extCfgEdit.topLevelItemCount()):
            witem = self.extCfgEdit.topLevelItem(i)
            items.append((witem.text(0), witem.text(1)))
        return items
コード例 #2
0
ファイル: mikibook.py プロジェクト: mjnaderi/mikidown
class NotebookExtSettingsDialog(QDialog):
    def __init__(self, parent=None, cfg_list=[]):
        super(NotebookExtSettingsDialog, self).__init__(parent)
        self.extCfgEdit = QTreeWidget()
        self.extCfgEdit.setHeaderLabels(['Property', 'Value'])
        self.addRow = QPushButton('+')
        self.removeRow = QPushButton('-')
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)

        layout = QGridLayout(self)
        layout.addWidget(self.extCfgEdit,0,0,1,2)
        layout.addWidget(self.addRow,1,0,1,1)
        layout.addWidget(self.removeRow,1,1,1,1)
        layout.addWidget(self.buttonBox,2,0,1,2)
        self.initCfgPanel(cfg_list)

        self.addRow.clicked.connect(self.actionAdd)
        self.removeRow.clicked.connect(self.actionRemove)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def initCfgPanel(self, cfg_list):
        for item in cfg_list:
            self.actionAdd(prop_name=item[0], prop_val=item[1])

    def actionRemove(self):
        item = self.extCfgEdit.currentItem()
        row = self.extCfgEdit.indexOfTopLevelItem(item)
        self.extCfgEdit.takeTopLevelItem(row)

    def actionAdd(self, checked=False, prop_name='', prop_val=''):
        item = QTreeWidgetItem(self.extCfgEdit, [prop_name, prop_val])
        item.setFlags(item.flags()|Qt.ItemIsEditable)
        #self.extCfgEdit.addTopLevelItem(item)

    def configToList(self):
        items = []
        for i in range(self.extCfgEdit.topLevelItemCount()):
            witem = self.extCfgEdit.topLevelItem(i)
            items.append((witem.text(0), witem.text(1)))
        return items
コード例 #3
0
class MainWindow(QtGui.QMainWindow):

    sig_update_tree = pyqtSignal(object, object, object)
    sig_show_overview_plot = pyqtSignal()

    def __init__(self, font, parent=None):
        super(MainWindow, self).__init__(parent)
        self.font = font
        self.setWindowTitle("Meridien")
        central_widget = QtGui.QWidget(self)
        self.setCentralWidget(central_widget)

        #Center on screen
        resolution = QtGui.QDesktopWidget().screenGeometry()
        self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
                  (resolution.height() / 2) - (self.frameSize().height() / 2))
        """
        Setting up menu bar
        """

        close_action = QtGui.QAction('Close', self)
        close_action.setShortcut("Ctrl+Q")
        close_action.setStatusTip('Leave the app')
        close_action.triggered.connect(lambda: self.close())

        open_refinement_folder = QtGui.QAction('Open Refinement Folder', self)
        open_refinement_folder.triggered.connect(self.open_refinement_folder)

        self.mainMenu = self.menuBar()
        self.fileMenu = self.mainMenu.addMenu('&File')
        self.fileMenu.addAction(open_refinement_folder)
        self.fileMenu.addAction(close_action)
        self.refinement_folder = ""

        create_new_fsc_plot = QtGui.QAction('&New FSC plot', self)
        create_new_fsc_plot.triggered.connect(
            self.event_ontriggered_show_fsc_plot)

        create_new_overview_plot = QtGui.QAction(
            '&New resolution overview plot', self)
        create_new_overview_plot.triggered.connect(
            self.event_show_resolution_overview_plot)
        self.plotMenu = self.mainMenu.addMenu('&Plot')
        self.plotMenu.addAction(create_new_fsc_plot)
        self.plotMenu.addAction(create_new_overview_plot)
        """
        Setup other components
        """
        self.layout = QGridLayout(central_widget)
        self.setMenuBar(self.mainMenu)

        self.tree = QTreeWidget(self)
        self.tree.setHeaderHidden(True)
        self.layout.addWidget(self.tree, 1, 0)

        self.root_items_path_dictionary = {}

        # Threads
        self.threadpool = QThreadPool()
        self.thread_list = []
        thr = QThread(self)
        thr.start()

        self.reader = DriverFileReader()
        self.reader.moveToThread(thr)
        self.thread_list.append(thr)
        self.timer = QTimer(self)

        # Connect signals
        self.reader.sig_sendfolders.connect(self.fill_tree)
        self.reader.sig_sendfsc.connect(self.show_dialog_fsc)
        self.tree.itemChanged.connect(self._event_select_deselect_all)
        self.sig_update_tree.connect(self.update_tree)
        self.sig_show_overview_plot.connect(
            self.event_show_resolution_overview_plot)
        self.show()
        self.open_refinement_folder()

        self.monitor = None

    @pyqtSlot(object, object, object)
    def update_tree(self, item, monitored_folder, delete):
        '''

        :param item: main folder to add to tree item belonging to folder montiored_folder
        :param monitored_folder: Refinement folder
        :param delete: if this is true, it will delete the monitored folder
        :return:
        '''
        if delete:
            root = self.root_items_path_dictionary[monitored_folder]
            index = self.tree.indexOfTopLevelItem(root)
            self.tree.takeTopLevelItem(index)
        else:
            root = self.root_items_path_dictionary[monitored_folder]
            root.addChild(item)
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText("Meridien - There is data of a new run: " +
                        str(item.text(0)))
            msg.setWindowTitle("Update")
            msg.exec_()

    @pyqtSlot(object, object, object, object)
    def show_dialog_fsc(self, *args):
        """
        Shows fsc plot
        :param args: list of arguments
        :return: None
        """
        fsc_plot = FSCPlot(self)
        fsc_plot.plot(*args)

    @pyqtSlot()
    def event_show_resolution_overview_plot(self):
        """
        Trigger for fsc plot
        :return: None
        """
        tracker_reader = TrackerFileReader()
        res_0143, res_05 = tracker_reader.read_res0143_and_res05(
            self.refinement_folder)

        res_plot = ResolutionOverviewPlot(parent=self)
        res_plot.setWindowTitle(self.refinement_folder)
        res_plot.plot(res_05, res_0143)

    def event_ontriggered_show_fsc_plot(self):
        """
        Trigger for fsc plot
        :return: none
        """
        checked_runs = self._get_checked_items()
        paths = []
        for checked_run in checked_runs:

            refinement_folder = checked_run.parent().text(0)

            path = os.path.join(str(refinement_folder),
                                str(checked_run.text(0)))

            paths.append(path)
        self.reader.sig_readfsc.emit(paths)

    def _event_select_deselect_all(self, root_tree_item):
        '''
        Checks all childs of root_tree_item
        :param root_tree_item: QTreeWidgetItem which represents a refinement folder
        :return:
        '''

        if root_tree_item in self.root_items_path_dictionary.values():
            number_of_runs = root_tree_item.childCount()
            for i in range(number_of_runs):
                child_run = root_tree_item.child(i)
                child_run.setCheckState(0, root_tree_item.checkState(0))

    def _get_checked_items(self):
        """
        Finds the checked elements in tree
        :return: List of checked QItemWidget
        """
        checked_runs = []
        for root in self.root_items_path_dictionary.values():
            number_of_runs = root.childCount()

            for i in range(number_of_runs):
                main_run = root.child(i)
                if main_run.checkState(0) == QtCore.Qt.Checked:
                    checked_runs.append(main_run)
        return checked_runs

    def open_refinement_folder(self):
        """
        Let the user choose the refinement folder and adds it to the RefinementFolder-Tree
        :return: none
        """
        self.refinement_folder = str(
            QtGui.QFileDialog.getExistingDirectory(
                self, "Select Refinement Directory"))
        if self.refinement_folder == "":
            return
        if self.refinement_folder in self.root_items_path_dictionary:
            return
        self._open_refinement_folder(self.refinement_folder)
        self.sig_show_overview_plot.emit()

    def _open_refinement_folder(self, path):
        """
        Reads the refinement folder, setup the folder daemon and signals
        :param path: Path to refinement folder

        """

        if path != '':

            #for i in reversed(range(self.root.childCount())):
            #    self.root.removeChild(self.root.child(i))
            name = os.path.basename(path)
            qname = QString(name)
            root = QtGui.QTreeWidgetItem([str(path)])
            self.root_items_path_dictionary[str(path)] = root
            self.tree.addTopLevelItem(root)
            fm = QFontMetrics(self.font)
            w = fm.width(path)
            self.tree.setMinimumWidth(w + 150)
            #self.root.setText(0, qname)
            self.reader.sig_readfolders.emit(path)
            self.monitor = MonitorRefinementFolder(path, self.sig_update_tree,
                                                   self)
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.monitor.update)
            self.timer.start(2000)

    def closeEvent(self, close_event):
        '''
        Closes all threads.
        '''
        for thr in self.thread_list:
            thr.quit()
            thr.wait()

    @pyqtSlot(object)
    def fill_tree(self, path_to_refinement_folder):
        '''
        Reads all runs in path_to_refinement_folder and add them as child to the corresponding root element in the tree
        :param path_to_refinement_folder: Path to refinement folder
        :return: none
        '''
        root = self.root_items_path_dictionary[str(path_to_refinement_folder)]
        root.setCheckState(0, QtCore.Qt.Unchecked)
        main_dicts = DriverFileReader.read_refinement_folders(
            path_to_refinement_folder)
        for dictionary in main_dicts:
            next_item = QtGui.QTreeWidgetItem([dictionary])
            next_item.setCheckState(0, QtCore.Qt.Unchecked)
            root.addChild(next_item)

    def close_application(self):
        '''
        Close the application
        :return: none
        '''
        sys.exit()
コード例 #4
0
ファイル: ui_tools.py プロジェクト: AlexaProjects/Alexa2
class AddToProject(QDialog):

    def __init__(self, pathProjects, parent=None):
        #pathProjects must be a list
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Add File to Project"))
        self.pathSelected = ''
        vbox = QVBoxLayout(self)

        self._tree = QTreeWidget()
        self._tree.header().setHidden(True)
        self._tree.setSelectionMode(QTreeWidget.SingleSelection)
        self._tree.setAnimated(True)
        vbox.addWidget(self._tree)
        hbox = QHBoxLayout()
        btnAdd = QPushButton(self.tr("Add here!"))
        btnCancel = QPushButton(self.tr("Cancel"))
        hbox.addWidget(btnCancel)
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        #load folders
        self._root = None
        self._loading_items = {}
        self.loading_projects(pathProjects)
        self._thread_execution = ThreadExecution(
            self._thread_load_projects, args=[pathProjects])
        self.connect(self._thread_execution,
                     SIGNAL("finished()"), self._callback_load_project)
        self._thread_execution.start()

        self.connect(btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(btnAdd, SIGNAL("clicked()"), self._select_path)

    def loading_projects(self, projects):
        for project in projects:
            loadingItem = LoadingItem()
            item = loadingItem.add_item_to_tree(project, self._tree,
                                                parent=self)
            self._loading_items[project] = item

    def _thread_load_projects(self, projects):
        structures = []
        for pathProject in projects:
            folderStructure = file_manager.open_project(pathProject)
            structures.append((folderStructure, pathProject))
        self._thread_execution.storage_values = structures

    def _callback_load_project(self):
        structures = self._thread_execution.storage_values
        if structures:
            for structure, path in structures:
                item = self._loading_items.pop(path, None)
                if item is not None:
                    index = self._tree.indexOfTopLevelItem(item)
                    self._tree.takeTopLevelItem(index)
                self._load_project(structure, path)

    def _select_path(self):
        item = self._tree.currentItem()
        if item:
            self.pathSelected = item.toolTip(0)
            self.close()

    def _load_project(self, folderStructure, folder):
        if not folder:
            return

        name = file_manager.get_basename(folder)
        item = QTreeWidgetItem(self._tree)
        item.setText(0, name)
        item.setToolTip(0, folder)
        item.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
        if folderStructure[folder][1] is not None:
            folderStructure[folder][1].sort()
        self._load_folder(folderStructure, folder, item)
        item.setExpanded(True)
        self._root = item

    def _load_folder(self, folderStructure, folder, parentItem):
        items = folderStructure[folder]

        if items[1] is not None:
            items[1].sort()
        for _file in items[1]:
            if _file.startswith('.'):
                continue
            subfolder = QTreeWidgetItem(parentItem)
            subfolder.setText(0, _file)
            subfolder.setToolTip(0, os.path.join(folder, _file))
            subfolder.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
            self._load_folder(folderStructure,
                              os.path.join(folder, _file), subfolder)
コード例 #5
0
ファイル: ui_tools.py プロジェクト: sbellem/ninja-ide
class AddToProject(QDialog):
    def __init__(self, pathProjects, parent=None):
        #pathProjects must be a list
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Add File to Project"))
        self.pathSelected = ''
        vbox = QVBoxLayout(self)

        self._tree = QTreeWidget()
        self._tree.header().setHidden(True)
        self._tree.setSelectionMode(QTreeWidget.SingleSelection)
        self._tree.setAnimated(True)
        vbox.addWidget(self._tree)
        hbox = QHBoxLayout()
        btnAdd = QPushButton(self.tr("Add here!"))
        btnCancel = QPushButton(self.tr("Cancel"))
        hbox.addWidget(btnCancel)
        hbox.addWidget(btnAdd)
        vbox.addLayout(hbox)
        #load folders
        self._root = None
        self._loading_items = {}
        self.loading_projects(pathProjects)
        self._thread_execution = ThreadExecution(self._thread_load_projects,
                                                 args=[pathProjects])
        self.connect(self._thread_execution, SIGNAL("finished()"),
                     self._callback_load_project)
        self._thread_execution.start()

        self.connect(btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(btnAdd, SIGNAL("clicked()"), self._select_path)

    def loading_projects(self, projects):
        for project in projects:
            loadingItem = LoadingItem()
            item = loadingItem.add_item_to_tree(project,
                                                self._tree,
                                                parent=self)
            self._loading_items[project] = item

    def _thread_load_projects(self, projects):
        structures = []
        for pathProject in projects:
            folderStructure = file_manager.open_project(pathProject)
            structures.append((folderStructure, pathProject))
        self._thread_execution.storage_values = structures

    def _callback_load_project(self):
        structures = self._thread_execution.storage_values
        for structure, path in structures:
            item = self._loading_items.pop(path, None)
            if item is not None:
                index = self._tree.indexOfTopLevelItem(item)
                self._tree.takeTopLevelItem(index)
            self._load_project(structure, path)

    def _select_path(self):
        item = self._tree.currentItem()
        if item:
            self.pathSelected = item.toolTip(0)
            self.close()

    def _load_project(self, folderStructure, folder):
        if not folder:
            return

        name = file_manager.get_basename(folder)
        item = QTreeWidgetItem(self._tree)
        item.setText(0, name)
        item.setToolTip(0, folder)
        item.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
        if folderStructure[folder][1] is not None:
            folderStructure[folder][1].sort()
        self._load_folder(folderStructure, folder, item)
        item.setExpanded(True)
        self._root = item

    def _load_folder(self, folderStructure, folder, parentItem):
        items = folderStructure[folder]

        if items[1] is not None:
            items[1].sort()
        for _file in items[1]:
            if _file.startswith('.'):
                continue
            subfolder = QTreeWidgetItem(parentItem)
            subfolder.setText(0, _file)
            subfolder.setToolTip(0, os.path.join(folder, _file))
            subfolder.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
            self._load_folder(folderStructure, os.path.join(folder, _file),
                              subfolder)
コード例 #6
0
ファイル: LibrarySearchDialog.py プロジェクト: mapancsu/mars2
class LibrarySearchDialog(QtGui.QDialog):
    def __init__(self, ms, parent=None):
        QtGui.QDialog.__init__(self, parent)
        settings = QSettings()
        size = settings.value("MainWindow/Size",
                              QVariant(QSize(1024, 600))).toSize()
        self.resize(size)

        self.setWindowTitle(
            'Identify unknown compound by mass spectra Library')
        self.ms = ms
        pms = processMS(ms)
        self.axis = pms[0]
        self.mass = pms[1]
        self.peak_MS = pms[2]
        self.maxmass = int(self.axis[-1])

        self.initControls()
        self.initPlots()

        self.selectedIndex = []
        self.percent = []
        self._cpointsPicker1 = Qwt.QwtPicker(self.plot1.canvas())
        self._cpointsPicker1.setSelectionFlags(Qwt.QwtPicker.PointSelection)
        self._cpointsPicker1.widgetMouseDoubleClickEvent = self.plot1MouseDoubleClickEvent

    def updatePlots(self):

        reply = QtGui.QMessageBox.question(
            self, 'EleComp Parameters',
            "Are you sure to Use Single Mass %s?" % self.selected_mz,
            QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            #            print self.x
            self.ElemCompDialog1()
#        self.m.setLabel(self.text1)
#       self.m.setValue(self.x, 0.0)
#        rowMs=int((self.x-self.scan_acquisition_time.data[0])/0.2)
#        self.showMs(rowMs)

#        self.plot1.replot()

    def plot1MouseDoubleClickEvent(self, event):
        self.xp = self.plot1.invTransform(Qwt.QwtPlot.xBottom, event.x())
        n1 = np.searchsorted(self.axis, self.xp - 1)
        n2 = np.searchsorted(self.axis, self.xp + 1)
        self.selected_mz = self.axis[np.argmax(self.mass[n1:n2]) + n1]
        print self.xp
        print self.selected_mz
        self.updatePlots()

    def ElemCompDialog1(self):
        dialog = ElemCompDialog(mz=self.axis,
                                mass=self.mass,
                                xp=self.selected_mz)
        dialog.move(QPoint(100, 10))
        res = dialog.exec_()

    def initControls(self):
        self.plot3 = Qwt.QwtPlot(self)
        self.plot3.setCanvasBackground(Qt.white)
        self.plot3.enableAxis(Qwt.QwtPlot.yLeft, False)
        self.plot3.enableAxis(Qwt.QwtPlot.xBottom, False)
        self.plot1 = Qwt.QwtPlot(self)
        self.plot1.setCanvasBackground(Qt.white)
        self.plot2 = Qwt.QwtPlot(self)
        self.plot2.setCanvasBackground(Qt.white)

        library_label = QLabel("MS in mass spectra Library:")
        self.library_list = QTreeWidget()
        self.library_list.setColumnCount(3)
        self.library_list.setHeaderLabels(
            ['No.', 'Similarity', 'Mol Wt', 'Formula', 'Name'])
        self.library_list.setSortingEnabled(False)
        self.connect(self.library_list, SIGNAL("itemSelectionChanged()"),
                     self.libraryListClicked)
        self.connect(self.library_list,
                     SIGNAL("itemActivated (QTreeWidgetItem *,int)"),
                     self.libraryListDoubleClicked)
        mxiture_label = QLabel("Molecular structure :")
        #        self.mixture_list = QListWidget()

        okButton = QPushButton("&Search")
        self.connect(okButton, SIGNAL("clicked()"), self.Seach)

        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.plot1)
        left_vbox.addWidget(self.plot2)

        right_vbox = QVBoxLayout()
        right_vbox.addWidget(library_label)
        right_vbox.addWidget(self.library_list)

        hboxPercent = QHBoxLayout()
        #        hboxPercent.addWidget(percent_label)
        #        hboxPercent.addWidget(self.edit_percent)
        right_vbox.addLayout(hboxPercent)

        #        right_vbox.addWidget(self.add_button)
        right_vbox.addWidget(mxiture_label)
        right_vbox.addWidget(self.plot3)
        right_vbox.addWidget(okButton)

        hbox = QHBoxLayout()
        hbox.addLayout(left_vbox, 2.5)
        hbox.addLayout(right_vbox, 1.5)
        self.setLayout(hbox)

        #self.setCentralWidget(self.main_frame)

    def initPlots(self):
        self.plot3.clear()
        self.plot3.setAxisScale(self.plot1.xBottom, -4, 4)
        self.plot3.setAxisScale(self.plot1.yLeft, -4, 4)
        self.plot1.clear()
        self.plot1.setTitle("Search MS")
        self.plot1.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity')
        grid = Qwt.QwtPlotGrid()
        pen = QPen(Qt.DotLine)
        pen.setColor(Qt.black)
        pen.setWidth(0)
        grid.setPen(pen)
        grid.attach(self.plot1)
        self.plot1.setAxisScale(self.plot1.yLeft, 0, 1.1 * np.max(self.mass))
        color = QColor('black')
        curve = Qwt.QwtPlotCurve("test1")
        pen = QPen(color)
        pen.setWidth(1)
        curve.setPen(pen)
        #self.axis= np.arange(len(self.mass))
        curve.setData(self.axis, self.mass)
        curve.setStyle(Qwt.QwtPlotCurve.Sticks)
        curve.attach(self.plot1)
        for i in range(len(self.peak_MS)):
            text_MS = Qwt.QwtText('%s' % (str(self.peak_MS[i][0])))
            marker_MS = Qwt.QwtPlotMarker()
            marker_MS.setLabelAlignment(Qt.AlignCenter | Qt.AlignTop)
            marker_MS.setLabel(text_MS)
            marker_MS.setValue(self.peak_MS[i][0], self.peak_MS[i][1])
            marker_MS.attach(self.plot1)
        self.plot1.replot()

        self.plot2.clear()
        self.plot2.setTitle("NIST MS")
        #        self.plot2.setAxisTitle(Qwt.QwtPlot.xBottom, 'Raman shift (cm-1)')
        self.plot2.setAxisTitle(Qwt.QwtPlot.yLeft, 'Intensity')
        grid = Qwt.QwtPlotGrid()
        pen = QPen(Qt.DotLine)
        pen.setColor(Qt.black)
        pen.setWidth(0)
        grid.setPen(pen)
        grid.attach(self.plot2)
        self.plot2.replot()

    def libraryListClicked(self):

        row = self.library_list.indexOfTopLevelItem(
            self.library_list.currentItem())
        self.row1 = self.masscor[row][0]
        print 'row: %s' % self.row1
        self.showMs(self.row1)

    def libraryListDoubleClicked(self, item, pos):
        dialog = NistLibraryDialog(num=self.row1)
        dialog.move(QPoint(100, 10))
        res = dialog.exec_()

    def showMs(self, row1):
        self.row1 = row1
        self.cur.execute(
            "select name,peakindex,peakintensity  from catalog where id=%d" %
            row1)
        temp = self.cur.fetchall()
        masstemp = np.frombuffer(temp[0][1], dtype=np.int)
        intensitytemp = np.frombuffer(temp[0][2], dtype=np.int)
        intensitytemp = 100 * intensitytemp / np.max(intensitytemp)
        row = np.zeros(len(masstemp))
        mass = coo_matrix((intensitytemp, (row, masstemp)),
                          shape=(1, ceil(masstemp[-1]) + 1)).todense()
        self.massSeacher = mass.tolist()
        radio_MS = 0.01 * (np.max(self.massSeacher[0]) -
                           np.min(self.massSeacher[0]))
        peak_MS = []
        for i in range(5, len(self.massSeacher[0]) - 5):
            if (self.massSeacher[0][i] == max(self.massSeacher[0][i - 5:i + 5])
                    and self.massSeacher[0][i] >= radio_MS):
                peak_intensity_MS = (i, self.massSeacher[0][i])
                peak_MS.append(peak_intensity_MS)
        self.plot2.clear()
        self.plot2.setTitle("MS of %s" % str(temp[0][0][:-2]))
        color = QColor('black')
        curve2 = Qwt.QwtPlotCurve("test1")
        pen = QPen(color)
        pen.setWidth(1)
        curve2.setPen(pen)
        self.axis2 = masstemp
        curve2.setData(masstemp, intensitytemp)
        curve2.setStyle(Qwt.QwtPlotCurve.Sticks)
        curve2.attach(self.plot2)
        for i in range(len(peak_MS)):
            text_MS = Qwt.QwtText('%s' % (str(peak_MS[i][0])))
            marker_MS = Qwt.QwtPlotMarker()
            marker_MS.setLabelAlignment(Qt.AlignCenter | Qt.AlignTop)
            marker_MS.setLabel(text_MS)
            marker_MS.setValue(peak_MS[i][0], peak_MS[i][1])
            marker_MS.attach(self.plot2)

        x = np.hstack((self.axis, self.axis2))
        x_min = np.min(x)
        x_max = np.max(x)
        y1_max = np.max(self.mass)
        y1_min = np.min(self.mass)
        y2_max = np.max(intensitytemp)
        y2_min = np.min(intensitytemp)

        self.plot1.setAxisScale(self.plot1.xBottom, 0, x_max * 1.1)
        self.plot2.setAxisScale(self.plot1.xBottom, 0, x_max * 1.1)
        self.plot1.setAxisScale(self.plot1.yLeft, 0, y1_max * 1.1)
        self.plot2.setAxisScale(self.plot1.yLeft, 0, y2_max * 1.1)

        self.plot1.replot()
        self.plot2.replot()
        self.ShowMolFile()

    def comnum(self):
        i = 0
        for x in self.findms:
            if x in self.basems:
                i = i + 1
        cor = i * 2.0 / (len(self.findms) + len(self.basems))
        return cor

    def Seach_ZDJ(self):
        self.findms = []
        (mz_bin, val_bin, peaks_bin) = processMS(binMS(self.ms))
        peaks_bin.sort(key=lambda d: d[1], reverse=True)
        self.peak_index = []
        self.peak_inten = []
        for i in range(0, len(peaks_bin)):
            self.peak_index.append(int(peaks_bin[i][0]))
            self.peak_inten.append(peaks_bin[i][1])
        if len(peaks_bin) < 10:
            self.findms = self.peak_index
        else:
            self.findms = self.peak_index[0:10]
        time0 = time.time()
        db = sqlite3.connect(NIST_DBPath)
        self.cur = db.cursor()
        self.cur.execute(
            "select id,top10peakindex from catalog where MW>%d-28 and MW<%d+28"
            % (self.maxmass, self.maxmass))
        self.c = self.cur.fetchall()
        ms = []

        for i in range(len(self.c)):
            self.basems = np.frombuffer(self.c[i][1], dtype=np.int)
            cor = self.comnum()
            if cor > 0.4:
                temp = (self.c[i][0], cor)
                ms.append(temp)
        print ms
        self.masscor = []
        tic = time.time()
        for i in range(len(ms)):
            self.cur.execute(
                "select peakindex, peakintensity  from catalog where id=%d" %
                (ms[i][0]))
            temp = self.cur.fetchall()
            masstemp = np.frombuffer(temp[0][0], dtype=np.int)
            intensitytemp = np.frombuffer(temp[0][1], dtype=np.int)
            temp2 = (ms[i][0],
                     corrcoef_ms(masstemp, intensitytemp, mz_bin, val_bin))
            self.masscor.append(temp2)
        print time.time() - time0
        print time.time() - tic
        self.masscor.sort(key=lambda d: d[1], reverse=True)
        for i in range(min(25, len(ms))):
            self.cur.execute(
                "select name,Formula,MW  from catalog where id=%d" %
                self.masscor[i][0])
            temp = self.cur.fetchall()
            strsimilarity = '%.2f' % self.masscor[i][1]
            temp3 = temp[0][1][:-1]
            temp1 = temp[0][2]
            temp2 = temp[0][0][:-2]
            item = QTreeWidgetItem([
                str(i + 1),
                str(strsimilarity),
                str(temp1),
                str(temp3),
                str(temp2)
            ])
            self.library_list.addTopLevelItem(item)

        if len(ms) > 0:
            self.showMs(self.masscor[0][0])

        zoomer = Qwt.QwtPlotZoomer(Qwt.QwtPlot.xBottom, Qwt.QwtPlot.yLeft,
                                   Qwt.QwtPicker.DragSelection,
                                   Qwt.QwtPicker.AlwaysOn, self.plot1.canvas())
        zoomer.setRubberBandPen(QPen(Qt.black))
        zoomer.setTrackerPen(QPen(Qt.blue))
        self.plot1.zoomer = zoomer
        self.plot1.zoomer.setZoomBase()

    def Seach(self):

        ms = self.ms
        nist = NISTSearch(NIST_DBPath)
        nist.top10_screen(self.ms)
        nist.corr()
        self.masscor = nist.corrs

        db = sqlite3.connect(NIST_DBPath)
        self.cur = db.cursor()
        for i in range(min(25, len(self.masscor))):
            self.cur.execute(
                "select name,Formula,MW  from catalog where id=%d" %
                self.masscor[i][0])
            temp = self.cur.fetchall()
            strsimilarity = '%.2f' % self.masscor[i][1]
            temp3 = temp[0][1][:-1]
            temp1 = temp[0][2]
            temp2 = temp[0][0][:-2]
            item = QTreeWidgetItem([
                str(i + 1),
                str(strsimilarity),
                str(temp1),
                str(temp3),
                str(temp2)
            ])
            self.library_list.addTopLevelItem(item)

        if len(ms) > 0:
            self.showMs(self.masscor[0][0])

        zoomer = Qwt.QwtPlotZoomer(Qwt.QwtPlot.xBottom, Qwt.QwtPlot.yLeft,
                                   Qwt.QwtPicker.DragSelection,
                                   Qwt.QwtPicker.AlwaysOn, self.plot1.canvas())
        zoomer.setRubberBandPen(QPen(Qt.black))
        zoomer.setTrackerPen(QPen(Qt.blue))
        self.plot1.zoomer = zoomer
        self.plot1.zoomer.setZoomBase()

    def ShowMolFile(self):
        self.plot3.clear()
        self.ID = self.row1
        Molecular = {}
        db = sqlite3.connect(MOL_DBPath)
        cur = db.cursor()
        cur.execute("select * from catalog where id=%d" % self.ID)
        c = cur.fetchall()
        Molecular["MolName"] = c[0][1]
        Molecular["MolNum"] = c[0][2]
        Molecular["MolBondNum"] = c[0][3]
        Molecular["Mol"] = c[0][4].split()
        Molecular["MolXAxis"] = np.frombuffer(c[0][5], dtype=np.float)
        Molecular["MolYAxis"] = np.frombuffer(c[0][6], dtype=np.float)
        Molecular["MolStyle"] = np.frombuffer(c[0][7], dtype=np.int)
        Molecular["bondX"] = np.frombuffer(c[0][8], dtype=np.int)
        Molecular["bondY"] = np.frombuffer(c[0][9], dtype=np.int)
        Molecular["bondNum"] = np.frombuffer(c[0][10], dtype=np.int)
        self.Molecular = Molecular
        color = QColor('black')
        curve = Qwt.QwtPlotCurve()
        pen = QPen(color)
        pen.setWidth(1)
        curve.setPen(pen)
        curve.setStyle(Qwt.QwtPlotCurve.NoCurve)
        curve.setSymbol(
            Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.black, QPen(Qt.black),
                          QSize(3, 3)))
        curve.attach(self.plot3)
        curve.setData(self.Molecular["MolXAxis"], self.Molecular["MolYAxis"])
        tempstyl1 = []
        tempstyl2 = []
        tempstyl3 = []
        tempstyl4 = []
        for i in range(Molecular["MolBondNum"]):
            if Molecular["bondNum"][i] == 1 and Molecular["MolStyle"][
                    Molecular["bondX"][i] -
                    1] == 0 and Molecular["MolStyle"][Molecular["bondY"][i] -
                                                      1] == 0:
                tempstyl2.append(Molecular["bondX"][i])
                tempstyl2.append(Molecular["bondY"][i])
        for i in range(Molecular["MolBondNum"]):
            if Molecular["bondNum"][i] == 2 and Molecular["MolStyle"][
                    Molecular["bondX"][i] -
                    1] == 0 and Molecular["MolStyle"][Molecular["bondY"][i] -
                                                      1] == 0:
                if (Molecular["bondX"][i]
                        in tempstyl2) and (Molecular["bondY"][i] in tempstyl2):
                    tempstyl1.append(Molecular["bondX"][i])
                    tempstyl1.append(Molecular["bondY"][i])
        for i in range(len(tempstyl2) / 2):
            if (tempstyl2[2 * i] in tempstyl1) and (tempstyl2[2 * i + 1]
                                                    in tempstyl1):
                tempstyl3.append(tempstyl2[2 * i])
                tempstyl3.append(tempstyl2[2 * i + 1])
        for i in range(len(tempstyl1) / 2):
            if (tempstyl1[2 * i] in tempstyl3) and (tempstyl1[2 * i + 1]
                                                    in tempstyl3):
                tempstyl4.append(tempstyl1[2 * i])
                tempstyl4.append(tempstyl1[2 * i + 1])
        tempstyl6 = []
        for i in range(len(tempstyl3) / 2):
            if (tempstyl3[2 * i] in tempstyl4) and (tempstyl3[2 * i + 1]
                                                    in tempstyl4):
                tempstyl6.append(tempstyl3[2 * i])
                tempstyl6.append(tempstyl3[2 * i + 1])
        tempstyl5 = []
        #            print tempstyl4
        while True:
            if len(tempstyl6) == 0 or len(tempstyl4) == 0:
                break
            for i in range(len(tempstyl4) / 2):
                #                print i
                if not (tempstyl4[2 * i] in tempstyl5):
                    tempindex3 = tempstyl6.index(tempstyl4[2 * i])
                    tempindex4 = tempstyl6.index(tempstyl4[2 * i + 1])
                    temp1 = tempstyl4[2 * i]
                    temp2 = tempstyl4[2 * i + 1]
                    if tempindex3 % 2 == 0:
                        temp3 = tempstyl6[tempindex3 + 1]
                        tempindex3other = tempindex3 + 1
                    else:
                        temp3 = tempstyl6[tempindex3 - 1]
                        tempindex3other = tempindex3 - 1
                    if tempindex4 % 2 == 0:
                        temp4 = tempstyl6[tempindex4 + 1]
                        tempindex4other = tempindex4 + 1
                    else:
                        temp4 = tempstyl6[tempindex4 - 1]
                        tempindex4other = tempindex4 - 1
                    tempindex5 = tempstyl4.index(temp3)
                    tempindex6 = tempstyl4.index(temp4)
                    if tempindex5 % 2 == 0:
                        temp5 = tempstyl4[tempindex5 + 1]
                    else:
                        temp5 = tempstyl4[tempindex5 - 1]
                    if tempindex6 % 2 == 0:
                        temp6 = tempstyl4[tempindex6 + 1]
                    else:
                        temp6 = tempstyl4[tempindex6 - 1]
                    tempindex7 = tempstyl6.index(temp5)
                    if tempindex7 % 2 == 0:
                        temp7 = tempstyl6[tempindex7 + 1]
                        tempindex7other = tempindex7 + 1
                    else:
                        temp7 = tempstyl6[tempindex7 - 1]
                        tempindex7other = tempindex7 - 1
                    if temp7 == temp6:
                        if not ((temp1 in tempstyl5) and
                                (temp2 in tempstyl5) and
                                (temp3 in tempstyl5) and
                                (temp4 in tempstyl5) and
                                (temp5 in tempstyl5) and (temp6 in tempstyl5)):
                            tempstyl5.append(temp1)
                            tempstyl5.append(temp2)
                            tempstyl5.append(temp4)
                            tempstyl5.append(temp3)
                            tempstyl5.append(temp6)
                            tempstyl5.append(temp5)
                            temp = [
                                tempindex3, tempindex3other, tempindex4,
                                tempindex4other, tempindex7, tempindex7other
                            ]
                            temp.sort(reverse=True)
                            del tempstyl6[temp[0]]
                            del tempstyl6[temp[1]]
                            del tempstyl6[temp[2]]
                            del tempstyl6[temp[3]]
                            del tempstyl6[temp[4]]
                            del tempstyl6[temp[5]]
                            for i in np.arange((len(tempstyl4) - 1) / 2, -1,
                                               -1):
                                if not (tempstyl4[2 * i] in tempstyl6) or not (
                                        tempstyl4[2 * i + 1] in tempstyl6):
                                    del tempstyl4[2 * i + 1]
                                    del tempstyl4[2 * i]
                            for i in np.arange((len(tempstyl6) - 1) / 2, -1,
                                               -1):
                                if not (tempstyl6[2 * i] in tempstyl4) or not (
                                        tempstyl6[2 * i + 1] in tempstyl4):
                                    del tempstyl6[2 * i + 1]
                                    del tempstyl6[2 * i]
                            for i in np.arange((len(tempstyl4) - 1) / 2, -1,
                                               -1):
                                if not (tempstyl4[2 * i] in tempstyl6) or not (
                                        tempstyl4[2 * i + 1] in tempstyl6):
                                    del tempstyl4[2 * i + 1]
                                    del tempstyl4[2 * i]
                            for i in np.arange((len(tempstyl6) - 1) / 2, -1,
                                               -1):
                                if not (tempstyl6[2 * i] in tempstyl4) or not (
                                        tempstyl6[2 * i + 1] in tempstyl4):
                                    del tempstyl6[2 * i + 1]
                                    del tempstyl6[2 * i]
                            break


#            tempstylCom=list(set(tempstyl1) & set(tempstyl2))
#            styl=np.setdiff1d(tempstyl1,tempstylCom)
        for i in range(Molecular["MolBondNum"]):
            x1 = self.Molecular["MolXAxis"][self.Molecular["bondX"][i] - 1]
            x2 = self.Molecular["MolXAxis"][self.Molecular["bondY"][i] - 1]
            y1 = self.Molecular["MolYAxis"][self.Molecular["bondX"][i] - 1]
            y2 = self.Molecular["MolYAxis"][self.Molecular["bondY"][i] - 1]
            if (y2 - y1) == 0:
                Xdiff = 0
                Ydiff = np.sqrt(0.003)
            else:
                h = (x2 - x1) / (y2 - y1)
                Xdiff = np.sqrt(0.003 / (h * h + 1))
                Ydiff = Xdiff * h
            if (Molecular["bondNum"][i]
                    == 2) and not (Molecular["bondX"][i] in tempstyl5):
                tempx1 = []
                tempy1 = []
                tempx2 = []
                tempy2 = []
                tempx1.append(x1 + Xdiff)
                tempx1.append(x2 + Xdiff)
                tempy1.append(y1 - Ydiff)
                tempy1.append(y2 - Ydiff)
                tempx2.append(x1 - Xdiff)
                tempx2.append(x2 - Xdiff)
                tempy2.append(y1 + Ydiff)
                tempy2.append(y2 + Ydiff)
                curve2 = Qwt.QwtPlotCurve()
                curve2.setStyle(Qwt.QwtPlotCurve.Lines)
                curve2.attach(self.plot3)
                curve2.setData(tempx1, tempy1)
                curve3 = Qwt.QwtPlotCurve()
                curve3.setStyle(Qwt.QwtPlotCurve.Lines)
                curve3.attach(self.plot3)
                curve3.setData(tempx2, tempy2)
            elif (Molecular["bondNum"][i] == 3):
                tempx = []
                tempy = []
                tempx.append(x1)
                tempx.append(x2)
                tempy.append(y1)
                tempy.append(y2)
                curve1 = Qwt.QwtPlotCurve()
                curve1.setStyle(Qwt.QwtPlotCurve.Lines)
                curve1.attach(self.plot3)
                curve1.setData(tempx, tempy)
                tempx1 = []
                tempy1 = []
                tempx2 = []
                tempy2 = []
                tempx1.append(x1 + Xdiff)
                tempx1.append(x2 + Xdiff)
                tempy1.append(y1 - Ydiff)
                tempy1.append(y2 - Ydiff)
                tempx2.append(x1 - Xdiff)
                tempx2.append(x2 - Xdiff)
                tempy2.append(y1 + Ydiff)
                tempy2.append(y2 + Ydiff)
                curve2 = Qwt.QwtPlotCurve()
                curve2.setStyle(Qwt.QwtPlotCurve.Lines)
                curve2.attach(self.plot3)
                curve2.setData(tempx1, tempy1)
                curve3 = Qwt.QwtPlotCurve()
                curve3.setStyle(Qwt.QwtPlotCurve.Lines)
                curve3.attach(self.plot3)
                curve3.setData(tempx2, tempy2)
            else:
                tempx = []
                tempy = []
                tempx.append(x1)
                tempx.append(x2)
                tempy.append(y1)
                tempy.append(y2)
                curve1 = Qwt.QwtPlotCurve()
                curve1.setStyle(Qwt.QwtPlotCurve.Lines)
                curve1.attach(self.plot3)
                curve1.setData(tempx, tempy)
        t = np.linspace(0, np.pi * 2, 100)
        diffx1 = np.sin(t) * 0.3
        diffy1 = np.cos(t) * 0.3
        for i in range(len(tempstyl5) / 6):
            x0 = 0
            y0 = 0
            diffx = []
            diffy = []
            x0 = Molecular["MolXAxis"][tempstyl5[
                6 * i] - 1] + Molecular["MolXAxis"][tempstyl5[6 * i + 1] - 1]
            x0 = x0 + Molecular["MolXAxis"][tempstyl5[6 * i + 2] -
                                            1] + Molecular["MolXAxis"][
                                                tempstyl5[6 * i + 3] - 1]
            x0 = x0 + Molecular["MolXAxis"][tempstyl5[6 * i + 4] -
                                            1] + Molecular["MolXAxis"][
                                                tempstyl5[6 * i + 5] - 1]
            x0 = x0 / 6
            y0 = Molecular["MolYAxis"][tempstyl5[
                6 * i] - 1] + Molecular["MolYAxis"][tempstyl5[6 * i + 1] - 1]
            y0 = y0 + Molecular["MolYAxis"][tempstyl5[6 * i + 2] -
                                            1] + Molecular["MolYAxis"][
                                                tempstyl5[6 * i + 3] - 1]
            y0 = y0 + Molecular["MolYAxis"][tempstyl5[6 * i + 4] -
                                            1] + Molecular["MolYAxis"][
                                                tempstyl5[6 * i + 5] - 1]
            y0 = y0 / 6
            for i in range(len(diffx1)):
                diffx.append(diffx1[i] + x0)
                diffy.append(diffy1[i] + y0)
            curve4 = Qwt.QwtPlotCurve()
            curve4.setStyle(Qwt.QwtPlotCurve.Lines)
            curve4.attach(self.plot3)
            curve4.setData(diffx, diffy)
        for i in range(Molecular["MolNum"]):
            if Molecular["MolStyle"][i] != 0:
                text = Qwt.QwtText('%s' % Molecular["Mol"][i])
                #                    text=Qwt.QwtText('%s'%str(i+1))
                text.setColor(Qt.blue)
                text.setFont(QFont("Sans", 12))
                text.setBackgroundBrush(Qt.white)
                marker = Qwt.QwtPlotMarker()
                marker.setLabelAlignment(Qt.AlignCenter | Qt.AlignCenter)
                marker.setLabel(text)
                marker.setValue(self.Molecular["MolXAxis"][i],
                                self.Molecular["MolYAxis"][i])
                marker.attach(self.plot3)
        self.plot3.setAxisScale(self.plot3.xBottom,
                                min((min(Molecular["MolXAxis"]) - 0.5), -4),
                                max((max(Molecular["MolXAxis"]) + 0.5), 4))
        self.plot3.setAxisScale(self.plot3.yLeft,
                                min((min(Molecular["MolYAxis"]) - 0.5), -4),
                                max((max(Molecular["MolYAxis"]) + 0.5), 4))
        self.plot3.replot()
コード例 #7
0
class EditorConfiguration(QWidget):
    """EditorConfiguration widget class"""
    def __init__(self, parent):
        super(EditorConfiguration, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)

        # groups
        group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT)
        group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN)
        group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT)
        group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT)
        group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS)
        group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE)
        group7 = QGroupBox(translations.TR_DISPLAY)

        # groups container
        container_widget_with_all_preferences = QWidget()
        formFeatures = QGridLayout(container_widget_with_all_preferences)

        # Indentation
        hboxg1 = QHBoxLayout(group1)
        hboxg1.setContentsMargins(5, 15, 5, 5)
        self._spin, self._checkUseTabs = QSpinBox(), QComboBox()
        self._spin.setRange(1, 10)
        self._spin.setValue(settings.INDENT)
        hboxg1.addWidget(self._spin)
        self._checkUseTabs.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(),
            translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()
        ])
        self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS))
        hboxg1.addWidget(self._checkUseTabs)
        formFeatures.addWidget(group1, 0, 0)

        # Margin Line
        hboxg2 = QHBoxLayout(group2)
        hboxg2.setContentsMargins(5, 15, 5, 5)
        self._checkShowMargin = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE)
        self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE)
        hboxg2.addWidget(self._checkShowMargin)
        self._spinMargin = QSpinBox()
        self._spinMargin.setRange(50, 100)
        self._spinMargin.setSingleStep(2)
        self._spinMargin.setValue(settings.MARGIN_LINE)
        hboxg2.addWidget(self._spinMargin)
        hboxg2.addWidget(QLabel(translations.TR_CHARACTERS))
        formFeatures.addWidget(group2, 0, 1)

        # Display Errors
        vboxDisplay = QVBoxLayout(group7)
        vboxDisplay.setContentsMargins(5, 15, 5, 5)
        self._checkHighlightLine = QComboBox()
        self._checkHighlightLine.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND,
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE
        ])
        self._checkHighlightLine.setCurrentIndex(
            int(settings.UNDERLINE_NOT_BACKGROUND))
        hboxDisplay1 = QHBoxLayout()
        hboxDisplay1.addWidget(QLabel(translations.TR_DISPLAY_ERRORS))
        hboxDisplay1.addWidget(self._checkHighlightLine)
        hboxDisplay2 = QHBoxLayout()
        self._checkDisplayLineNumbers = QCheckBox(
            translations.TR_DISPLAY_LINE_NUMBERS)
        self._checkDisplayLineNumbers.setChecked(settings.SHOW_LINE_NUMBERS)
        hboxDisplay2.addWidget(self._checkDisplayLineNumbers)
        vboxDisplay.addLayout(hboxDisplay1)
        vboxDisplay.addLayout(hboxDisplay2)
        formFeatures.addWidget(group7, 1, 0, 1, 0)

        # Find Lint Errors (highlighter)
        vboxg3 = QVBoxLayout(group3)
        self._checkErrors = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS)
        self._checkErrors.setChecked(settings.FIND_ERRORS)
        self.connect(self._checkErrors, SIGNAL("stateChanged(int)"),
                     self._disable_show_errors)
        self._showErrorsOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS)
        self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE)
        self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_errors_inline)
        vboxg3.addWidget(self._checkErrors)
        vboxg3.addWidget(self._showErrorsOnLine)
        vboxg3.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding))
        formFeatures.addWidget(group3, 2, 0)

        # Find PEP8 Errors (highlighter)
        vboxg4 = QHBoxLayout(group4)
        vboxg4.setContentsMargins(5, 15, 5, 5)
        vvbox = QVBoxLayout()
        self._checkStyle = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8)
        self._checkStyle.setChecked(settings.CHECK_STYLE)
        self.connect(self._checkStyle, SIGNAL("stateChanged(int)"),
                     self._disable_check_style)
        vvbox.addWidget(self._checkStyle)
        self._checkStyleOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8)
        self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE)
        self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_check_inline)
        vvbox.addWidget(self._checkStyleOnLine)
        vvbox.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding))
        vboxg4.addLayout(vvbox)
        # Container for tree widget and buttons
        widget = QWidget()
        hhbox = QHBoxLayout(widget)
        hhbox.setContentsMargins(0, 0, 0, 0)
        # Tree Widget with custom item delegate
        # always adds uppercase text
        self._listIgnoreViolations = QTreeWidget()
        self._listIgnoreViolations.setObjectName("ignore_pep8")
        self._listIgnoreViolations.setItemDelegate(ui_tools.CustomDelegate())
        self._listIgnoreViolations.setMaximumHeight(80)
        self._listIgnoreViolations.setHeaderLabel(
            translations.TR_PREFERENCES_EDITOR_CONFIG_IGNORE_PEP8)
        for ic in settings.IGNORE_PEP8_LIST:
            self._listIgnoreViolations.addTopLevelItem(QTreeWidgetItem([ic]))
        hhbox.addWidget(self._listIgnoreViolations)
        box = QVBoxLayout()
        box.setContentsMargins(0, 0, 0, 0)
        btn_add = QPushButton(QIcon(":img/add_small"), '')
        btn_add.setMaximumSize(26, 24)
        btn_add.clicked.connect(self._add_code_pep8)
        box.addWidget(btn_add)
        btn_remove = QPushButton(QIcon(":img/delete_small"), '')
        btn_remove.setMaximumSize(26, 24)
        btn_remove.clicked.connect(self._remove_code_pep8)
        box.addWidget(btn_remove)
        box.addItem(QSpacerItem(0, 0, QSizePolicy.Fixed,
                                QSizePolicy.Expanding))
        hhbox.addLayout(box)
        vboxg4.addWidget(widget)
        formFeatures.addWidget(group4)

        # Show Python3 Migration, DocStrings and Spaces (highlighter)
        vboxg5 = QVBoxLayout(group5)
        vboxg5.setContentsMargins(5, 15, 5, 5)
        self._showMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION)
        self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS)
        vboxg5.addWidget(self._showMigrationTips)
        self._checkForDocstrings = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS)
        self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS)
        vboxg5.addWidget(self._checkForDocstrings)
        self._checkShowSpaces = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES)
        self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES)
        vboxg5.addWidget(self._checkShowSpaces)
        self._checkIndentationGuide = QCheckBox(
            translations.TR_SHOW_INDENTATION_GUIDE)
        self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE)
        vboxg5.addWidget(self._checkIndentationGuide)
        formFeatures.addWidget(group5, 3, 0)

        # End of line, Stop Scrolling At Last Line, Trailing space, Word wrap
        vboxg6 = QVBoxLayout(group6)
        vboxg6.setContentsMargins(5, 15, 5, 5)
        self._checkEndOfLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
        self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
        vboxg6.addWidget(self._checkEndOfLine)
        self._checkEndAtLastLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE)
        self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE)
        vboxg6.addWidget(self._checkEndAtLastLine)
        self._checkTrailing = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
        self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
        vboxg6.addWidget(self._checkTrailing)
        self._allowWordWrap = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
        self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
        vboxg6.addWidget(self._allowWordWrap)
        formFeatures.addWidget(group6, 3, 1)

        # pack all the groups
        vbox.addWidget(container_widget_with_all_preferences)
        vbox.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    def _add_code_pep8(self):
        item = QTreeWidgetItem()
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self._listIgnoreViolations.addTopLevelItem(item)
        self._listIgnoreViolations.setCurrentItem(item)
        self._listIgnoreViolations.editItem(item, 0)

    def _remove_code_pep8(self):
        index = self._listIgnoreViolations.indexOfTopLevelItem(
            self._listIgnoreViolations.currentItem())
        self._listIgnoreViolations.takeTopLevelItem(index)

    def _enable_check_inline(self, val):
        """Method that takes a value to enable the inline style checking"""
        if val == Qt.Checked:
            self._checkStyle.setChecked(True)

    def _enable_errors_inline(self, val):
        """Method that takes a value to enable the inline errors checking"""
        if val == Qt.Checked:
            self._checkErrors.setChecked(True)

    def _disable_check_style(self, val):
        """Method that takes a value to disable the inline style checking"""
        if val == Qt.Unchecked:
            self._checkStyleOnLine.setChecked(False)

    def _disable_show_errors(self, val):
        """Method that takes a value to disable the inline errors checking"""
        if val == Qt.Unchecked:
            self._showErrorsOnLine.setChecked(False)

    def save(self):
        """Method to save settings"""
        qsettings = IDE.ninja_settings()
        settings.USE_TABS = bool(self._checkUseTabs.currentIndex())
        qsettings.setValue('preferences/editor/useTabs', settings.USE_TABS)
        margin_line = self._spinMargin.value()
        settings.MARGIN_LINE = margin_line
        settings.pycodestylemod_update_margin_line_length(margin_line)
        qsettings.setValue('preferences/editor/marginLine', margin_line)
        settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
        qsettings.setValue('preferences/editor/showMarginLine',
                           settings.SHOW_MARGIN_LINE)
        settings.INDENT = self._spin.value()
        qsettings.setValue('preferences/editor/indent', settings.INDENT)
        endOfLine = self._checkEndOfLine.isChecked()
        settings.USE_PLATFORM_END_OF_LINE = endOfLine
        qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine)
        settings.UNDERLINE_NOT_BACKGROUND = \
            bool(self._checkHighlightLine.currentIndex())
        qsettings.setValue('preferences/editor/errorsUnderlineBackground',
                           settings.UNDERLINE_NOT_BACKGROUND)
        settings.FIND_ERRORS = self._checkErrors.isChecked()
        qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS)
        settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked()
        qsettings.setValue('preferences/editor/errorsInLine',
                           settings.ERRORS_HIGHLIGHT_LINE)
        settings.CHECK_STYLE = self._checkStyle.isChecked()
        qsettings.setValue('preferences/editor/checkStyle',
                           settings.CHECK_STYLE)
        settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked()
        qsettings.setValue('preferences/editor/showMigrationTips',
                           settings.SHOW_MIGRATION_TIPS)
        settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked()
        qsettings.setValue('preferences/editor/checkStyleInline',
                           settings.CHECK_HIGHLIGHT_LINE)
        settings.END_AT_LAST_LINE = self._checkEndAtLastLine.isChecked()
        qsettings.setValue('preferences/editor/endAtLastLine',
                           settings.END_AT_LAST_LINE)
        settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked()
        qsettings.setValue('preferences/editor/removeTrailingSpaces',
                           settings.REMOVE_TRAILING_SPACES)
        settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked()
        qsettings.setValue('preferences/editor/allowWordWrap',
                           settings.ALLOW_WORD_WRAP)
        settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked()
        qsettings.setValue('preferences/editor/showTabsAndSpaces',
                           settings.SHOW_TABS_AND_SPACES)
        settings.SHOW_INDENTATION_GUIDE = (
            self._checkIndentationGuide.isChecked())
        qsettings.setValue('preferences/editor/showIndentationGuide',
                           settings.SHOW_INDENTATION_GUIDE)
        settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked()
        qsettings.setValue('preferences/editor/checkForDocstrings',
                           settings.CHECK_FOR_DOCSTRINGS)
        settings.SHOW_LINE_NUMBERS = self._checkDisplayLineNumbers.isChecked()
        qsettings.setValue('preferences/editor/showLineNumbers',
                           settings.SHOW_LINE_NUMBERS)
        current_ignores = set(settings.IGNORE_PEP8_LIST)
        new_ignore_codes = []
        # Get pep8 from tree widget
        for index in range(self._listIgnoreViolations.topLevelItemCount()):
            ignore_code = self._listIgnoreViolations.topLevelItem(index).text(
                0)
            if ignore_code:
                new_ignore_codes.append(ignore_code.strip())
        # pep8 list that will be removed
        to_remove = [x for x in current_ignores if x not in new_ignore_codes]
        # Update list
        settings.IGNORE_PEP8_LIST = new_ignore_codes
        qsettings.setValue('preferences/editor/defaultIgnorePep8',
                           settings.IGNORE_PEP8_LIST)
        # Add
        for ignore_code in settings.IGNORE_PEP8_LIST:
            settings.pycodestylemod_add_ignore(ignore_code)
        # Remove
        for ignore_code in to_remove:
            settings.pycodestylemod_remove_ignore(ignore_code)
        if settings.USE_TABS:
            settings.pycodestylemod_add_ignore("W191")
        else:
            settings.pycodestylemod_remove_ignore("W191")
コード例 #8
0
class EditorConfiguration(QWidget):
    """EditorConfiguration widget class"""

    def __init__(self, parent):
        super(EditorConfiguration, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)

        # groups
        group1 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_INDENT)
        group2 = QGroupBox(translations.TR_PREFERENCES_EDITOR_CONFIG_MARGIN)
        group3 = QGroupBox(translations.TR_LINT_DIRTY_TEXT)
        group4 = QGroupBox(translations.TR_PEP8_DIRTY_TEXT)
        group5 = QGroupBox(translations.TR_HIGHLIGHTER_EXTRAS)
        group6 = QGroupBox(translations.TR_TYPING_ASSISTANCE)
        group7 = QGroupBox(translations.TR_DISPLAY)

        # groups container
        container_widget_with_all_preferences = QWidget()
        formFeatures = QGridLayout(container_widget_with_all_preferences)

        # Indentation
        hboxg1 = QHBoxLayout(group1)
        hboxg1.setContentsMargins(5, 15, 5, 5)
        self._spin, self._checkUseTabs = QSpinBox(), QComboBox()
        self._spin.setRange(1, 10)
        self._spin.setValue(settings.INDENT)
        hboxg1.addWidget(self._spin)
        self._checkUseTabs.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_SPACES.capitalize(),
            translations.TR_PREFERENCES_EDITOR_CONFIG_TABS.capitalize()])
        self._checkUseTabs.setCurrentIndex(int(settings.USE_TABS))
        hboxg1.addWidget(self._checkUseTabs)
        formFeatures.addWidget(group1, 0, 0)

        # Margin Line
        hboxg2 = QHBoxLayout(group2)
        hboxg2.setContentsMargins(5, 15, 5, 5)
        self._checkShowMargin = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MARGIN_LINE)
        self._checkShowMargin.setChecked(settings.SHOW_MARGIN_LINE)
        hboxg2.addWidget(self._checkShowMargin)
        self._spinMargin = QSpinBox()
        self._spinMargin.setRange(50, 100)
        self._spinMargin.setSingleStep(2)
        self._spinMargin.setValue(settings.MARGIN_LINE)
        hboxg2.addWidget(self._spinMargin)
        hboxg2.addWidget(QLabel(translations.TR_CHARACTERS))
        formFeatures.addWidget(group2, 0, 1)

        # Display Errors
        vboxDisplay = QVBoxLayout(group7)
        vboxDisplay.setContentsMargins(5, 15, 5, 5)
        self._checkHighlightLine = QComboBox()
        self._checkHighlightLine.addItems([
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_BACKGROUND,
            translations.TR_PREFERENCES_EDITOR_CONFIG_ERROR_USE_UNDERLINE])
        self._checkHighlightLine.setCurrentIndex(
            int(settings.UNDERLINE_NOT_BACKGROUND))
        hboxDisplay1 = QHBoxLayout()
        hboxDisplay1.addWidget(QLabel(translations.TR_DISPLAY_ERRORS))
        hboxDisplay1.addWidget(self._checkHighlightLine)
        hboxDisplay2 = QHBoxLayout()
        self._checkDisplayLineNumbers = QCheckBox(
            translations.TR_DISPLAY_LINE_NUMBERS)
        self._checkDisplayLineNumbers.setChecked(settings.SHOW_LINE_NUMBERS)
        hboxDisplay2.addWidget(self._checkDisplayLineNumbers)
        vboxDisplay.addLayout(hboxDisplay1)
        vboxDisplay.addLayout(hboxDisplay2)
        formFeatures.addWidget(group7, 1, 0, 1, 0)

        # Find Lint Errors (highlighter)
        vboxg3 = QVBoxLayout(group3)
        self._checkErrors = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_FIND_ERRORS)
        self._checkErrors.setChecked(settings.FIND_ERRORS)
        self.connect(self._checkErrors, SIGNAL("stateChanged(int)"),
                     self._disable_show_errors)
        self._showErrorsOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_ERRORS)
        self._showErrorsOnLine.setChecked(settings.ERRORS_HIGHLIGHT_LINE)
        self.connect(self._showErrorsOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_errors_inline)
        vboxg3.addWidget(self._checkErrors)
        vboxg3.addWidget(self._showErrorsOnLine)
        vboxg3.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding))
        formFeatures.addWidget(group3, 2, 0)

        # Find PEP8 Errors (highlighter)
        vboxg4 = QHBoxLayout(group4)
        vboxg4.setContentsMargins(5, 15, 5, 5)
        vvbox = QVBoxLayout()
        self._checkStyle = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_PEP8)
        self._checkStyle.setChecked(settings.CHECK_STYLE)
        self.connect(self._checkStyle, SIGNAL("stateChanged(int)"),
                     self._disable_check_style)
        vvbox.addWidget(self._checkStyle)
        self._checkStyleOnLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TOOLTIP_PEP8)
        self._checkStyleOnLine.setChecked(settings.CHECK_HIGHLIGHT_LINE)
        self.connect(self._checkStyleOnLine, SIGNAL("stateChanged(int)"),
                     self._enable_check_inline)
        vvbox.addWidget(self._checkStyleOnLine)
        vvbox.addItem(QSpacerItem(0, 0,
                      QSizePolicy.Expanding, QSizePolicy.Expanding))
        vboxg4.addLayout(vvbox)
        # Container for tree widget and buttons
        widget = QWidget()
        hhbox = QHBoxLayout(widget)
        hhbox.setContentsMargins(0, 0, 0, 0)
        # Tree Widget with custom item delegate
        # always adds uppercase text
        self._listIgnoreViolations = QTreeWidget()
        self._listIgnoreViolations.setObjectName("ignore_pep8")
        self._listIgnoreViolations.setItemDelegate(ui_tools.CustomDelegate())
        self._listIgnoreViolations.setMaximumHeight(80)
        self._listIgnoreViolations.setHeaderLabel(
            translations.TR_PREFERENCES_EDITOR_CONFIG_IGNORE_PEP8)
        for ic in settings.IGNORE_PEP8_LIST:
            self._listIgnoreViolations.addTopLevelItem(QTreeWidgetItem([ic]))
        hhbox.addWidget(self._listIgnoreViolations)
        box = QVBoxLayout()
        box.setContentsMargins(0, 0, 0, 0)
        btn_add = QPushButton(QIcon(":img/add_small"), '')
        btn_add.setMaximumSize(26, 24)
        btn_add.clicked.connect(self._add_code_pep8)
        box.addWidget(btn_add)
        btn_remove = QPushButton(QIcon(":img/delete_small"), '')
        btn_remove.setMaximumSize(26, 24)
        btn_remove.clicked.connect(self._remove_code_pep8)
        box.addWidget(btn_remove)
        box.addItem(QSpacerItem(0, 0,
                    QSizePolicy.Fixed, QSizePolicy.Expanding))
        hhbox.addLayout(box)
        vboxg4.addWidget(widget)
        formFeatures.addWidget(group4)

        # Show Python3 Migration, DocStrings and Spaces (highlighter)
        vboxg5 = QVBoxLayout(group5)
        vboxg5.setContentsMargins(5, 15, 5, 5)
        self._showMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_MIGRATION)
        self._showMigrationTips.setChecked(settings.SHOW_MIGRATION_TIPS)
        vboxg5.addWidget(self._showMigrationTips)
        self._checkForDocstrings = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_CHECK_FOR_DOCSTRINGS)
        self._checkForDocstrings.setChecked(settings.CHECK_FOR_DOCSTRINGS)
        vboxg5.addWidget(self._checkForDocstrings)
        self._checkShowSpaces = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_SHOW_TABS_AND_SPACES)
        self._checkShowSpaces.setChecked(settings.SHOW_TABS_AND_SPACES)
        vboxg5.addWidget(self._checkShowSpaces)
        self._checkIndentationGuide = QCheckBox(
            translations.TR_SHOW_INDENTATION_GUIDE)
        self._checkIndentationGuide.setChecked(settings.SHOW_INDENTATION_GUIDE)
        vboxg5.addWidget(self._checkIndentationGuide)
        formFeatures.addWidget(group5, 3, 0)

        # End of line, Stop Scrolling At Last Line, Trailing space, Word wrap
        vboxg6 = QVBoxLayout(group6)
        vboxg6.setContentsMargins(5, 15, 5, 5)
        self._checkEndOfLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_OF_LINE)
        self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
        vboxg6.addWidget(self._checkEndOfLine)
        self._checkEndAtLastLine = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE)
        self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE)
        vboxg6.addWidget(self._checkEndAtLastLine)
        self._checkTrailing = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
        self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
        vboxg6.addWidget(self._checkTrailing)
        self._allowWordWrap = QCheckBox(
            translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
        self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
        vboxg6.addWidget(self._allowWordWrap)
        formFeatures.addWidget(group6, 3, 1)

        # pack all the groups
        vbox.addWidget(container_widget_with_all_preferences)
        vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                     QSizePolicy.Expanding))

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    def _add_code_pep8(self):
        item = QTreeWidgetItem()
        item.setFlags(item.flags() | Qt.ItemIsEditable)
        self._listIgnoreViolations.addTopLevelItem(item)
        self._listIgnoreViolations.setCurrentItem(item)
        self._listIgnoreViolations.editItem(item, 0)

    def _remove_code_pep8(self):
        index = self._listIgnoreViolations.indexOfTopLevelItem(
            self._listIgnoreViolations.currentItem())
        self._listIgnoreViolations.takeTopLevelItem(index)

    def _enable_check_inline(self, val):
        """Method that takes a value to enable the inline style checking"""
        if val == Qt.Checked:
            self._checkStyle.setChecked(True)

    def _enable_errors_inline(self, val):
        """Method that takes a value to enable the inline errors checking"""
        if val == Qt.Checked:
            self._checkErrors.setChecked(True)

    def _disable_check_style(self, val):
        """Method that takes a value to disable the inline style checking"""
        if val == Qt.Unchecked:
            self._checkStyleOnLine.setChecked(False)

    def _disable_show_errors(self, val):
        """Method that takes a value to disable the inline errors checking"""
        if val == Qt.Unchecked:
            self._showErrorsOnLine.setChecked(False)

    def save(self):
        """Method to save settings"""
        qsettings = IDE.ninja_settings()
        settings.USE_TABS = bool(self._checkUseTabs.currentIndex())
        qsettings.setValue('preferences/editor/useTabs',
                           settings.USE_TABS)
        margin_line = self._spinMargin.value()
        settings.MARGIN_LINE = margin_line
        settings.pycodestylemod_update_margin_line_length(margin_line)
        qsettings.setValue('preferences/editor/marginLine', margin_line)
        settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
        qsettings.setValue('preferences/editor/showMarginLine',
                           settings.SHOW_MARGIN_LINE)
        settings.INDENT = self._spin.value()
        qsettings.setValue('preferences/editor/indent', settings.INDENT)
        endOfLine = self._checkEndOfLine.isChecked()
        settings.USE_PLATFORM_END_OF_LINE = endOfLine
        qsettings.setValue('preferences/editor/platformEndOfLine', endOfLine)
        settings.UNDERLINE_NOT_BACKGROUND = \
            bool(self._checkHighlightLine.currentIndex())
        qsettings.setValue('preferences/editor/errorsUnderlineBackground',
                           settings.UNDERLINE_NOT_BACKGROUND)
        settings.FIND_ERRORS = self._checkErrors.isChecked()
        qsettings.setValue('preferences/editor/errors', settings.FIND_ERRORS)
        settings.ERRORS_HIGHLIGHT_LINE = self._showErrorsOnLine.isChecked()
        qsettings.setValue('preferences/editor/errorsInLine',
                           settings.ERRORS_HIGHLIGHT_LINE)
        settings.CHECK_STYLE = self._checkStyle.isChecked()
        qsettings.setValue('preferences/editor/checkStyle',
                           settings.CHECK_STYLE)
        settings.SHOW_MIGRATION_TIPS = self._showMigrationTips.isChecked()
        qsettings.setValue('preferences/editor/showMigrationTips',
                           settings.SHOW_MIGRATION_TIPS)
        settings.CHECK_HIGHLIGHT_LINE = self._checkStyleOnLine.isChecked()
        qsettings.setValue('preferences/editor/checkStyleInline',
                           settings.CHECK_HIGHLIGHT_LINE)
        settings.END_AT_LAST_LINE = self._checkEndAtLastLine.isChecked()
        qsettings.setValue('preferences/editor/endAtLastLine',
                           settings.END_AT_LAST_LINE)
        settings.REMOVE_TRAILING_SPACES = self._checkTrailing.isChecked()
        qsettings.setValue('preferences/editor/removeTrailingSpaces',
                           settings.REMOVE_TRAILING_SPACES)
        settings.ALLOW_WORD_WRAP = self._allowWordWrap.isChecked()
        qsettings.setValue('preferences/editor/allowWordWrap',
                           settings.ALLOW_WORD_WRAP)
        settings.SHOW_TABS_AND_SPACES = self._checkShowSpaces.isChecked()
        qsettings.setValue('preferences/editor/showTabsAndSpaces',
                           settings.SHOW_TABS_AND_SPACES)
        settings.SHOW_INDENTATION_GUIDE = (
            self._checkIndentationGuide.isChecked())
        qsettings.setValue('preferences/editor/showIndentationGuide',
                           settings.SHOW_INDENTATION_GUIDE)
        settings.CHECK_FOR_DOCSTRINGS = self._checkForDocstrings.isChecked()
        qsettings.setValue('preferences/editor/checkForDocstrings',
                           settings.CHECK_FOR_DOCSTRINGS)
        settings.SHOW_LINE_NUMBERS = self._checkDisplayLineNumbers.isChecked()
        qsettings.setValue('preferences/editor/showLineNumbers',
                           settings.SHOW_LINE_NUMBERS)
        current_ignores = set(settings.IGNORE_PEP8_LIST)
        new_ignore_codes = []
        # Get pep8 from tree widget
        for index in range(self._listIgnoreViolations.topLevelItemCount()):
            ignore_code = self._listIgnoreViolations.topLevelItem(
                index).text(0)
            if ignore_code:
                new_ignore_codes.append(ignore_code.strip())
        # pep8 list that will be removed
        to_remove = [x for x in current_ignores
                     if x not in new_ignore_codes]
        # Update list
        settings.IGNORE_PEP8_LIST = new_ignore_codes
        qsettings.setValue('preferences/editor/defaultIgnorePep8',
                           settings.IGNORE_PEP8_LIST)
        # Add
        for ignore_code in settings.IGNORE_PEP8_LIST:
            settings.pycodestylemod_add_ignore(ignore_code)
        # Remove
        for ignore_code in to_remove:
            settings.pycodestylemod_remove_ignore(ignore_code)
        if settings.USE_TABS:
            settings.pycodestylemod_add_ignore("W191")
        else:
            settings.pycodestylemod_remove_ignore("W191")