Пример #1
0
    def setupUi(self):
        self.resize(640, 480)
        self.verticalLayout = QVBoxLayout(self)
        self.textEdit = QPlainTextEdit(self)
        self.closeButton = QPushButton(self)
        self.copyButton = QPushButton(self)

        self.verticalLayout.addWidget(self.textEdit)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.horizontalLayout.addWidget(self.copyButton)
        self.horizontalLayout.addWidget(self.closeButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.closeButton.clicked.connect(self.reject)

        font = QFont(CONFIG['text_view_dialog_font'], CONFIG['text_view_dialog_font_size'])
        font.setStyleHint(QFont.Monospace)
        self.textEdit.setFont(font)

        self.closeButton.setText('Close')
        self.copyButton.setText('Copy to clipboard')
        self.textEdit.setPlainText(self.text)
        self.copyButton.clicked.connect(self.copy_text)
Пример #2
0
	def set_header_style(self):

		fnt = QFont()
		fnt.setWeight(QFont.Black)
		self.setFont(fnt)
		self.setBackground(QBrush(QColor(HEADER_BACKGROUND)))
		self.setForeground(QBrush(QColor(HEADER_FOREGROUND)))
Пример #3
0
def get_font(section='appearance', option='font', font_size_delta=0):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))

    if font is None:
        families = CONF.get(section, option+"/family", None)

        if families is None:
            return QFont()

        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option+'/italic', False)

        if CONF.get(section, option+'/bold', False):
            weight = QFont.Bold

        size = CONF.get(section, option+'/size', 9) + font_size_delta
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font

    size = CONF.get(section, option+'/size', 9) + font_size_delta
    font.setPointSize(size)
    return font
Пример #4
0
    def createInfoLayout():
        info_layout = QVBoxLayout()

        ert = QLabel()
        ert.setAlignment(Qt.AlignHCenter)

        title_font = QFont()
        title_font.setPointSize(40)
        ert.setFont(title_font)
        ert.setText("ERT")

        info_layout.addWidget(ert)
        info_layout.addStretch(1)
        ert_title = QLabel()
        ert_title.setAlignment(Qt.AlignHCenter)
        ert_title.setText("Ensemble based Reservoir Tool")
        info_layout.addWidget(ert_title)

        version = QLabel()

        version.setAlignment(Qt.AlignHCenter)
        version.setText(
            "Versions: ecl:%s    res:%s    ert:%s" %
            (ecl.__version__, res.__version__, ert_gui.__version__))
        info_layout.addWidget(version)

        info_layout.addStretch(5)

        return info_layout
Пример #5
0
  def heightForWidth(self, width, defaultFont=None):
      """
      Find the height for a given width
 
      :param float width: Width
      :param QFont defaultFont: Font, used for the calculation if the text has no font
      :return: Calculated height
      """
      if defaultFont is None:
          defaultFont = QFont()
      font = QFont(self.usedFont(defaultFont), self._desktopwidget)
      h = 0
      if self.__data.layoutAttributes & self.MinimumLayout:
          (left, right, top,
           bottom) = self.__data.textEngine.textMargins(font)
          h = self.__data.textEngine.heightForWidth(font,
                                                    self.__data.renderFlags,
                                                    self.__data.text,
                                                    width + left + right)
          h -= top + bottom
      else:
          h = self.__data.textEngine.heightForWidth(font,
                                                    self.__data.renderFlags,
                                                    self.__data.text, width)
      return h
Пример #6
0
def add_reprojections(scene, points, projected, inliers, boards, valid_boards,
                      options):
    marker_font = QFont()
    marker_font.setPixelSize(options.marker_size * 0.75)

    frame_table = points._extend(proj=projected.points, inlier=inliers)

    colors = struct(error_line=(1, 1, 0),
                    outlier=(1, 0, 0),
                    inlier=(0, 1, 0),
                    invalid=(0.5, 0.5, 0))

    pens = colors._map(cosmetic_pen, options.line_width)

    for board, valid_board, board_points in zip(boards, valid_boards,
                                                frame_table._sequence(0)):
        if not valid_board:
            continue

        for point, id in zip(board_points._sequence(), board.ids):

            color_key = 'invalid' if not point.valid else (
                'inlier' if point.inlier else 'outlier')
            add_marker(scene, point.proj, id, options, pens[color_key],
                       colors[color_key], marker_font)

            if point.valid:
                scene.addItem(line(point.proj, point.points, pens.error_line))
Пример #7
0
    def __init__(self, parent=None):
        super(Console, self).__init__(parent)
        self.json_decode_warning = None

        self.widget = QWidget(self)
        self.console_layout = QVBoxLayout(self.widget)
        self.widget.setLayout(self.console_layout)

        self.output_label = QLabel(self.widget)
        self.output_label.setText("Output")
        self.output_edit = QTextEdit(self.widget)
        self.output_edit.setReadOnly(True)
        self.highlighter = Highlighter(self.output_edit.document())
        self.output_edit.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.output_edit.setTextColor(QColor(0, 255, 0))
        self.output_edit.setFont(QFont(self.output_edit.currentFont().family(), 10))

        self.input_label = QLabel(self.widget)
        self.input_label.setText("Command")
        self.input_edit = QLineEdit(self.widget)
        self.input_edit.setStyleSheet("background-color: rgb(0, 0, 0); color: rgb(0, 255, 0)")
        self.input_edit.setFont(QFont(self.output_edit.currentFont().family(), 10))

        self.send_button = QPushButton(self.widget)
        self.send_button.setObjectName("send_button")
        self.send_button.setText("Send command")

        self.console_layout.addWidget(self.output_label)
        self.console_layout.addWidget(self.output_edit)
        self.console_layout.addWidget(self.input_label)
        self.console_layout.addWidget(self.input_edit)
        self.console_layout.addWidget(self.send_button)

        self.addContentWidget(self.widget)
        QMetaObject.connectSlotsByName(self)
Пример #8
0
 def add_series(self, chan_info):
     glw = self.findChild(pg.GraphicsLayoutWidget)
     new_plot = glw.addPlot(row=len(self.rasters), col=0)
     # Appearance settings
     my_theme = THEMES[self.plot_config['theme']]
     self.plot_config['color_iterator'] = (
         self.plot_config['color_iterator'] + 1) % len(
             my_theme['pencolors'])
     pen_color = QColor(
         my_theme['pencolors'][self.plot_config['color_iterator']])
     # Create PlotCurveItem for latest spikes (bottom row) and slower-updating old spikes (upper rows)
     pcis = []
     for pci_ix in range(2):
         pci = pg.PlotCurveItem(parent=new_plot, connect='pairs')
         pci.setPen(pen_color)
         new_plot.addItem(pci)
         pcis.append(pci)
     # Create text for displaying firing rate. Placeholder text is channel label.
     frate_annotation = pg.TextItem(text=chan_info['label'],
                                    color=(255, 255, 255))
     frate_annotation.setPos(0, self.plot_config['y_range'])
     my_font = QFont()
     my_font.setPointSize(24)
     frate_annotation.setFont(my_font)
     new_plot.addItem(frate_annotation)
     # Store information
     self.rasters[chan_info['label']] = {
         'plot': new_plot,
         'old': pcis[0],
         'latest': pcis[1],
         'line_ix': len(self.rasters),
         'chan_id': chan_info['chan'],
         'frate_item': frate_annotation
     }
     self.clear()
Пример #9
0
    def __init__(self, obj, obj_name='', attr_cols=None, parent=None):
        """
        Constructor

        :param obj: any Python object or variable
        :param obj_name: name of the object as it will appear in the root node
                         If empty, no root node will be drawn.
        :param attr_cols: list of AttributeColumn definitions
        :param parent: the parent widget
        """
        super(TreeModel, self).__init__(parent)
        self._attr_cols = attr_cols

        self.regular_font = QFont()  # Font for members (non-functions)
        # Font for __special_attributes__
        self.special_attribute_font = QFont()
        self.special_attribute_font.setItalic(False)

        self.regular_color = QBrush(QColor(ima.MAIN_FG_COLOR))
        self.callable_color = QBrush(QColor(
            ima.MAIN_FG_COLOR))  # for functions, methods, etc.

        # The following members will be initialized by populateTree
        # The rootItem is always invisible. If the obj_name
        # is the empty string, the inspectedItem
        # will be the rootItem (and therefore be invisible).
        # If the obj_name is given, an
        # invisible root item will be added and the
        # inspectedItem will be its only child.
        # In that case the inspected item will be visible.
        self._inspected_node_is_visible = None
        self._inspected_item = None
        self._root_item = None
        self.populateTree(obj, obj_name=obj_name)
Пример #10
0
def editor_bot(qtbot):
    """Editorstack pytest fixture."""
    text = ("   123\n"
            "line 1\n"
            "line 2\n"
            "line 3\n"
            "line 4")  # a newline is added at end
    editor_stack = EditorStack(None, [])

    # Fix the area of the selection
    font = QFont("Courier New")
    font.setPointSize(10)
    editor_stack.set_default_font(font)
    editor_stack.setMinimumWidth(400)
    editor_stack.setMinimumHeight(400)

    editor_stack.set_find_widget(Mock())
    editor_stack.set_io_actions(Mock(), Mock(), Mock(), Mock())
    finfo = editor_stack.new(osp.join(LOCATION, "foo.py"), "utf-8", text)
    editor_stack.new(osp.join(LOCATION, "foo1.py"), "utf-8", text)
    editor_stack.new(osp.join(LOCATION, "foo2.py"), "utf-8", text)
    editor_stack.new(osp.join(LOCATION, "foo3.py"), "utf-8", text)
    main = MainMock(editor_stack)

    # Hide GUI
    # qtbot.addWidget(main)
    # return main, editor_stack, finfo.editor, qtbot

    # Show GUI
    main.show()
    yield main, editor_stack, finfo.editor, qtbot
    main.destroy()
Пример #11
0
    def set_header_style(self):

        fnt = QFont()
        fnt.setWeight(QFont.Black)
        self.setFont(fnt)
        self.setBackground(QBrush(QColor(HEADER_BACKGROUND)))
        self.setForeground(QBrush(QColor(HEADER_FOREGROUND)))
Пример #12
0
    def __init__(self, parent, statusbar, icon=None):
        """Status bar widget base."""
        super(StatusBarWidget, self).__init__(parent)

        # Variables
        self.value = None

        # Widget
        self._status_bar = statusbar
        self._icon = None
        self._pixmap = None
        self._icon_size = QSize(16, 16)  # Should this be adjustable?
        self.label_icon = QLabel()
        self.label_value = QLabel()

        # Layout setup
        layout = QHBoxLayout(self)
        layout.setSpacing(0)  # Reduce space between icon and label
        layout.addWidget(self.label_icon)
        layout.addWidget(self.label_value)
        layout.addSpacing(20)
        layout.setContentsMargins(0, 0, 0, 0)

        # Widget setup
        self.set_icon(icon)

        # See spyder-ide/spyder#9044.
        self.text_font = QFont(QFont().defaultFamily(), weight=QFont.Normal)
        self.label_value.setAlignment(Qt.AlignRight)
        self.label_value.setFont(self.text_font)

        # Setup
        statusbar.addPermanentWidget(self)
        self.set_value('')
        self.update_tooltip()
Пример #13
0
def qwtUnscaleFont(painter):
    if painter.font().pixelSize() >= 0:
        return
    dpix, dpiy = get_screen_resolution()
    pd = painter.device()
    if pd.logicalDpiX() != dpix or pd.logicalDpiY() != dpiy:
        pixelFont = QFont(painter.font(), QApplication.desktop())
        pixelFont.setPixelSize(QFontInfo(pixelFont).pixelSize())
        painter.setFont(pixelFont)
Пример #14
0
def add_point_markers(scene, points, board, color, options):
    marker_font = QFont()
    marker_font.setPixelSize(options.marker_size * 0.75)

    pen = cosmetic_pen(color, options.line_width)
    corners = points.points[points.valid]

    for corner, id in zip(corners, board.ids[points.valid]):
        add_marker(scene, corner, id, options, pen, color, marker_font)
Пример #15
0
 def __init__(self, parent=None):
     """Constructor."""
     QAbstractItemModel.__init__(self, parent)
     self.abbreviator = Abbreviator()
     self.testresults = []
     try:
         self.monospace_font = parent.window().editor.get_plugin_font()
     except AttributeError:  # If run standalone for testing
         self.monospace_font = QFont("Courier New")
         self.monospace_font.setPointSize(10)
Пример #16
0
def qwtUnscaleFont(painter):
    if painter.font().pixelSize() >= 0:
        return
    screenResolution = qwtScreenResolution()
    pd = painter.device()
    if (pd.logicalDpiX() != screenResolution.width()
            or pd.logicalDpiY() != screenResolution.height()):
        pixelFont = QFont(painter.font(), QApplication.desktop())
        pixelFont.setPixelSize(QFontInfo(pixelFont).pixelSize())
        painter.setFont(pixelFont)
Пример #17
0
def get_code_block():
    if is_pygments and IS_SCINTILLA:
        #self.enter_data = QSyntaxHighlighting()
        enter_data = SimplePythonEditorWidget()
    else:
        enter_data = QTextEditAdd()
        font = QFont()
        font.setFamily('Courier')
        enter_data.setFont(font)
    return enter_data
Пример #18
0
 def updateRowData(self, r, path):
     it0 = QTableWidgetItem('%s ' % '/'.join(path.split('/')[:-1]))
     it0.setFont(QFont("Courier"))
     self._tb.setItem(r, 0, it0)
     it1 = QTableWidgetItem('%s ' % path.split('/')[-1])
     it1.parent = self
     ft = QFont("Courier")
     ft.setWeight(QFont.Bold)
     it1.setFont(ft)
     self._tb.setItem(r, 1, it1)
     node = self._model.nodeFromPath(path)
     if node:
         it1 = QTableWidgetItem(node.data(COLUMN_SIDS))
         it1.parent = self
         it2 = QTableWidgetItem(node.data(COLUMN_DATATYPE))
         it2.parent = self
         val = node.data(COLUMN_VALUE)
         if val == HIDEVALUE:
             val = QIcon(QPixmap(":/images/icons/data-array-large.png"))
             it3 = QTableWidgetItem(val, '')
         else:
             it3 = QTableWidgetItem(val)
             it3.setFont(QFont("Courier"))
         it3.parent = self
         it1.setFont(QFont("Courier"))
         it2.setFont(QFont("Courier"))
         it3.setFont(QFont("Courier"))
         self._tb.setItem(r, 2, it1)
         self._tb.setItem(r, 3, it2)
         self._tb.setItem(r, 4, it3)
Пример #19
0
    def set_layout(self):
        """Set layout for default widgets."""
        # Icon
        if self.show_icon:
            self._icon = self.get_icon()
            self._pixmap = None
            self._icon_size = QSize(16, 16)  # Should this be adjustable?
            self.label_icon = QLabel()
            self.set_icon()

        # Label
        if self.show_label:
            self.label_value = QLabel()
            self.set_value('')

            # See spyder-ide/spyder#9044.
            self.text_font = QFont(QFont().defaultFamily(),
                                   weight=QFont.Normal)
            self.label_value.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.label_value.setFont(self.text_font)

        # Custom widget
        if self.CUSTOM_WIDGET_CLASS:
            if not issubclass(self.CUSTOM_WIDGET_CLASS, QWidget):
                raise SpyderAPIError(
                    'Any custom status widget must subclass QWidget!')
            self.custom_widget = self.CUSTOM_WIDGET_CLASS(self._parent)

        # Spinner
        if self.show_spinner:
            self.spinner = create_waitspinner(size=14, parent=self)
            self.spinner.hide()

        # Layout setup
        layout = QHBoxLayout(self)
        layout.setSpacing(0)  # Reduce space between icon and label
        if self.show_icon:
            layout.addWidget(self.label_icon)
        if self.show_label:
            layout.addWidget(self.label_value)
        if self.custom_widget:
            layout.addWidget(self.custom_widget)
        if self.show_spinner:
            layout.addWidget(self.spinner)

        if is_dark_interface():
            layout.addSpacing(0)
        else:
            layout.addSpacing(10)

        layout.setContentsMargins(0, 0, 0, 0)
        layout.setAlignment(Qt.AlignVCenter)

        # Setup
        self.update_tooltip()
Пример #20
0
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not len(self.data):
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(0, Qt.DisplayRole, "No results to show.")
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for testcase in self.data:
            testcase_item = QTreeWidgetItem(self)
            testcase_item.setData(
                1, Qt.DisplayRole, "{0}.{1}".format(
                    testcase.get("classname"), testcase.get("name")))
            testcase_item.setData(
                3, Qt.DisplayRole, float(testcase.get("time")) * 1e3)

            if len(testcase):
                test_error = testcase[0]

                status = test_error.tag
                testcase_item.setData(0, Qt.DisplayRole, status)
                color = COLORS[status]
                for col in range(self.columnCount()):
                    testcase_item.setBackground(col, color)

                type_ = test_error.get("type")
                message = test_error.get("message")
                if type_ and message:
                    text = "{0}: {1}".format(type_, message)
                elif type_:
                    text = type_
                else:
                    text = message
                testcase_item.setData(2, Qt.DisplayRole, text)

                text = test_error.text
                if text:
                    for line in text.rstrip().split("\n"):
                        error_content_item = QTreeWidgetItem(testcase_item)
                        error_content_item.setData(
                            0, Qt.DisplayRole, line)
                        error_content_item.setFirstColumnSpanned(True)
                        error_content_item.setFont(0, monospace_font)
            else:
                testcase_item.setData(0, Qt.DisplayRole, "ok")
Пример #21
0
    def set_font(self, font):

        self.fontSize = font.pointSize()
        self.homename_label.setFont(font)
        self.rooms_label.setFont(font)
        self.posteddate_label.setFont(font)
        self.description_label.setFont(font)
        self.title_label.setFont(
            QFont(font.family(), self.fontSize + 3, QFont.DemiBold))
        self.price_label.setFont(
            QFont(font.family(), self.fontSize + 3, QFont.DemiBold))
Пример #22
0
    def changeEvent(self, event):
        if event.type() == QEvent.FontChange:
            fontsize = self.app.font().pointSize()

            # labels
            self.lb_machsht.label.setStyleSheet('QLabel{font-size: ' +
                                                str(fontsize + 35) + 'pt;}')
            self.lb_curr.setStyleSheet('QLabel{background-color: ' +
                                       self.app_color + ';'
                                       'font-size: ' + str(fontsize + 35) +
                                       'pt;}')
            self.lb_lifetime.setStyleSheet('QLabel{font-size: ' +
                                           str(fontsize + 35) + 'pt;}')
            self.tune_mon.lb_tunefrach.setStyleSheet('QLabel{font-size: ' +
                                                     str(fontsize + 35) +
                                                     'pt;}')
            self.tune_mon.lb_tunefracv.setStyleSheet('QLabel{font-size: ' +
                                                     str(fontsize + 35) +
                                                     'pt;}')

            self._gbox_siriusintlk.setStyleSheet('QGroupBox{font-size: ' +
                                                 str(fontsize + 2) + 'pt;'
                                                 'font-weight: bold;}')
            self._gbox_injsyssts.setStyleSheet('QGroupBox{font-size: ' +
                                               str(fontsize + 2) + 'pt;'
                                               'font-weight: bold;}')
            self._gbox_sofbloop.setStyleSheet('QGroupBox{font-size: ' +
                                              str(fontsize + 2) + 'pt;'
                                              'font-weight: bold;}')
            self._gbox_bbbloop.setStyleSheet('QGroupBox{font-size: ' +
                                             str(fontsize + 2) + 'pt;'
                                             'font-weight: bold;}')

            # graph
            graph_fontsize = fontsize + 2
            for ax in self.curr_graph.getPlotItem().axes.values():
                sty = ax['item'].labelStyle
                sty['font-size'] = str(graph_fontsize) + 'pt'
                ax['item'].setLabel(text=None, **sty)

            font = QFont()
            font.setPointSize(graph_fontsize)
            self.curr_graph.plotItem.getAxis('bottom').setStyle(
                tickTextOffset=5,
                autoExpandTextSpace=False,
                tickTextWidth=80,
                tickFont=font)
            self.curr_graph.plotItem.getAxis('left').setStyle(
                tickTextOffset=5,
                autoExpandTextSpace=False,
                tickTextWidth=80,
                tickFont=font)

            self.ensurePolished()
Пример #23
0
 def addPathEntry(self, parent, path, state, top=False):
     it = QTreeWidgetItem(parent, (path, ))
     ft = QFont(OCTXT._Table_Font)
     if top:
         ft.setBold(True)
     it.setFont(0, ft)
     if state == CGM.CHECK_FAIL:
         it.setIcon(0, self.IC(QW.I_C_SFL))
     if state == CGM.CHECK_WARN:
         it.setIcon(0, self.IC(QW.I_C_SWR))
     return it
Пример #24
0
    def __init__(self):
        super(PreprocessParameters, self).__init__()

        self.parameter = Parameter(name='params', type='group',
                                   children=[{'name': "Preprocess method",
                                              'values': ['Kohler_EMSC','Rubberband'],
                                              'value': 'Kohler_EMSC',
                                              'type': 'list'},
                                             {'name': "Anchor points",
                                              'value': '400, 4000',
                                              'type': 'str'},
                                             {'name': "Fitting regions",
                                              'value': '[(650, 750),(1780, 2680),(3680, 4000)]',
                                              'type': 'str'},
                                             {'name': "Interp method",
                                              'value': 'linear',
                                              'values': ['linear', 'quadratic', 'cubic'],
                                              'type': 'list'}
                                             ])
        self.setParameters(self.parameter, showTop=False)
        self.setIndentation(0)
        self.parameter.child('Interp method').hide()
        self.parameter.child('Anchor points').hide()

        # change Fonts
        self.fontSize = 12
        font = QFont("Helvetica [Cronyx]", self.fontSize)
        boldFont = QFont("Helvetica [Cronyx]", self.fontSize, QFont.Bold)
        self.header().setFont(font)
        for item in self.listAllItems():
            if hasattr(item, 'widget'):
                item.setFont(0, boldFont)
                item.widget.setFont(font)
                item.displayLabel.setFont(font)
                item.widget.setMaximumHeight(40)
        # init params dict
        self.argMap = {"Anchor points": 'anchors',
                       "Interp method": 'kind',
                       "Fitting regions": 'w_regions'
                       }
        # set self.processArgs to default value
        self.processArgs = {}
        for child in self.parameter.childs:
            if child.name() == "Anchor points":
                self.processArgs['anchors'] = '400, 4000'
            elif child.name() == "Interp method":
                self.processArgs['kind'] = 'linear'
            elif child.name() == "Fitting regions":
                self.processArgs['w_regions'] = '[(650, 750), (1780, 2680), (3680, 4000)]'

        # connect signals
        self.parameter.child('Preprocess method').sigValueChanged.connect(self.updateMethod)
        for name in self.argMap.keys():
            self.parameter.child(name).sigValueChanged.connect(partial(self.updateParam, name))
Пример #25
0
 def render__label_qfont(self, qfont: QFont):
     self.cfg.render.label_font = attr.evolve(
         self.cfg.render.label_font,
         # Font file selection
         family=qfont.family(),
         bold=qfont.bold(),
         italic=qfont.italic(),
         # Font size
         size=qfont.pointSizeF(),
         # QFont implementation details
         toString=qfont.toString(),
     )
Пример #26
0
    def load_from_config(self):
        # Appearance page
        self.darkThemeDefaultCheckBox.setChecked(CONFIG['dark_theme_default'])

        self.loggerTableFont.setCurrentFont(QFont(CONFIG['logger_table_font']))
        self.loggerTableFontSize.setValue(CONFIG['logger_table_font_size'])
        self.textViewFont.setCurrentFont(QFont(
            CONFIG['text_view_dialog_font']))
        self.textViewFontSize.setValue(CONFIG['text_view_dialog_font_size'])
        self.loggerTableRowHeight.setValue(CONFIG['logger_row_height'])
        self.excIndicationComboBox.setCurrentIndex(
            CONFIG['exception_indication'])
        self.timeFormatLine.setText(CONFIG['time_format_string'])
        self.timeFormatLine.setValidator(self.time_format_validator)
        self.timeFormatLine.textChanged.connect(self.time_format_valid)

        # Search
        self.searchOpenDefaultCheckBox.setChecked(
            CONFIG['search_open_default'])
        self.searchRegexDefaultCheckBox.setChecked(
            CONFIG['search_regex_default'])
        self.searchCaseSensitiveDefaultCheckBox.setChecked(
            CONFIG['search_casesensitive_default'])
        self.searchWildcardDefaultCheckBox.setChecked(
            CONFIG['search_wildcard_default'])

        # Server page
        self.listenHostLine.setText(CONFIG['listen_host'])
        self.listenPortLine.setValidator(QIntValidator(0, 65535, self))
        self.listenPortLine.setText(str(CONFIG['listen_port']))
        self.singleTabCheckBox.setChecked(CONFIG['single_tab_mode_default'])
        self.extraModeCheckBox.setChecked(CONFIG['extra_mode_default'])
        self.useSystemProxyCheckBox.setChecked(CONFIG['use_system_proxy'])
        if MSGPACK_SUPPORT:
            self.serializationFormatCombo.addItem("msgpack")
        if CBOR_SUPPORT:
            self.serializationFormatCombo.addItem("cbor")
        i = self.serializationFormatCombo.findText(
            CONFIG['default_serialization_format'])
        if i != -1:
            self.serializationFormatCombo.setCurrentIndex(i)

        # Advanced page
        self.logLevelLine.setValidator(QIntValidator(0, 1000, self))
        self.logLevelLine.setText(str(CONFIG['console_logging_level']))
        self.benchmarkCheckBox.setChecked(CONFIG['benchmark'])
        self.benchmarkIntervalLine.setValidator(
            QDoubleValidator(0, 1000, 9, self))
        self.benchmarkIntervalLine.setText(str(CONFIG['benchmark_interval']))
        self.lightThemeNativeCheckBox.setChecked(
            CONFIG['light_theme_is_native'])
        self.server_restart_needed = False
Пример #27
0
    def font(self, prefix, size):
        """Returns QFont corresponding to the given prefix and size

        Arguments
        ---------
        prefix: str
            prefix string of the loaded font
        size: int
            size for the font
        """
        font = QFont(self.fontname[prefix])
        font.setPixelSize(size)
        return font
Пример #28
0
    def font(self, prefix, size):
        """Returns QFont corresponding to the given prefix and size

        Arguments
        ---------
        prefix: str
            prefix string of the loaded font
        size: int
            size for the font
        """
        font = QFont(self.fontname[prefix])
        font.setPixelSize(size)
        return font
Пример #29
0
    def set_data(self, data: List[dict], headers: Optional[List[str]] = None):
        """Set the data in the table, given a list of dicts.

        Parameters
        ----------
        data : List[dict]
            A list of dicts where each dict in the list is a row, and each key
            in the dict is a header, by default None.  (call set_data later to
            add data)
        headers : list of str, optional
            If provided, will be used in order as the headers of the table. All
            items in ``headers`` must be present in at least one of the dicts.
            by default headers will be the set of all keys in all dicts in
            ``source``
        """
        if not isinstance(data, list) or any(
            not isinstance(i, dict) for i in data
        ):
            raise ValueError("'data' argument must be a list of dicts")
        nrows = len(data)
        _headers = sorted(set().union(*data))
        if headers:
            for h in headers:
                if h not in _headers:
                    raise ValueError(
                        trans._(
                            "Argument 'headers' got item '{h}', which was not found in any of the items in 'data'".format(
                                h=h
                            )
                        )
                    )
            _headers = headers
        self.setRowCount(nrows)
        self.setColumnCount(len(_headers))
        for row, elem in enumerate(data):
            for key, value in elem.items():
                value = value or ''
                try:
                    col = _headers.index(key)
                except ValueError:
                    continue
                item = QTableWidgetItem(value)
                # underline links
                if email_pattern.match(value) or url_pattern.match(value):
                    font = QFont()
                    font.setUnderline(True)
                    item.setFont(font)
                self.setItem(row, col, item)

        self.setHorizontalHeaderLabels(_headers)
        self.resize_to_fit()
Пример #30
0
class StatusBarWidget(QWidget):
    """Status bar widget base."""
    TIP = None

    def __init__(self, parent, statusbar, icon=None):
        """Status bar widget base."""
        super(StatusBarWidget, self).__init__(parent)

        # Variables
        self.value = None

        # Widget
        self._icon = icon
        self._pixmap = icon.pixmap(QSize(16, 16)) if icon is not None else None
        self.label_icon = QLabel() if icon is not None else None
        self.label_value = QLabel()

        # Widget setup
        if icon is not None:
            self.label_icon.setPixmap(self._pixmap)
        # See spyder-ide/spyder#9044.
        self.text_font = QFont(get_font(option='font'))
        self.text_font.setPointSize(self.font().pointSize())
        self.text_font.setBold(True)
        self.label_value.setAlignment(Qt.AlignRight)
        self.label_value.setFont(self.text_font)

        if self.TIP:
            self.setToolTip(self.TIP)
            self.label_value.setToolTip(self.TIP)

        # Layout
        layout = QHBoxLayout()
        if icon is not None:
            layout.addWidget(self.label_icon)
        layout.addWidget(self.label_value)
        layout.addSpacing(20)

        # Layout setup
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # Setup
        statusbar.addPermanentWidget(self)

    def set_value(self, value):
        """Set formatted text value."""
        self.value = value
        if self.isVisible():
            self.label_value.setText(value)
Пример #31
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.titleLabel = QLabel()
        font = QFont()
        font.setPointSize(72)
        self.titleLabel.setFont(font)
        self.iconLabel = QLabel()
        layout = QHBoxLayout()
        layout.addWidget(self.iconLabel)
        layout.addWidget(self.titleLabel)
        print("boom")

        self.setTitle("Terminal")
        self.setIcon("terminal")
Пример #32
0
class StatusBarWidget(QWidget):
    """Status bar widget base."""
    TIP = None

    def __init__(self, parent, statusbar, icon=None):
        """Status bar widget base."""
        super(StatusBarWidget, self).__init__(parent)

        # Variables
        self.value = None

        # Widget
        self._icon = icon
        self._pixmap = icon.pixmap(QSize(16, 16)) if icon is not None else None
        self.label_icon = QLabel() if icon is not None else None
        self.label_value = QLabel()

        # Widget setup
        if icon is not None:
            self.label_icon.setPixmap(self._pixmap)
        self.text_font = QFont(get_font(option='font'))  # See Issue #9044
        self.text_font.setPointSize(self.font().pointSize())
        self.text_font.setBold(True)
        self.label_value.setAlignment(Qt.AlignRight)
        self.label_value.setFont(self.text_font)

        if self.TIP:
            self.setToolTip(self.TIP)
            self.label_value.setToolTip(self.TIP)

        # Layout
        layout = QHBoxLayout()
        if icon is not None:
            layout.addWidget(self.label_icon)
        layout.addWidget(self.label_value)
        layout.addSpacing(20)

        # Layout setup
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # Setup
        statusbar.addPermanentWidget(self)

    def set_value(self, value):
        """Set formatted text value."""
        self.value = value
        if self.isVisible():
            self.label_value.setText(value)
Пример #33
0
 def font(self, prefix, size):
     """Return a QFont corresponding to the given prefix and size."""
     font = QFont()
     font.setFamily(self.fontname[prefix])
     font.setPixelSize(round(size))
     if prefix[-1] == 's':  # solid style
         font.setStyleName('Solid')
     return font
Пример #34
0
def _resize_widgets(build_popup, visible):

    output = build_popup.textBrowser_output
    cmd = build_popup.lineEdit_cmd

    font = QFont('Monospace' if visible else '')
    font.setStyleHint(QFont.TypeWriter)

    metrics = QFontMetrics(font)
    output.setFont(font)
    mw = build_popup.min_width = metrics.width(' ' * 80)
    output.setMinimumSize(QSize(mw,
                                20*metrics.height()))
    cmd.setMinimumSize(QSize(metrics.width(' ' * 40),
                             metrics.height()))
Пример #35
0
    def set_font_size(self, font_size):
        """
        Updates the font size of all objects in the PyDialog

        Parameters
        ----------
        font_size : int
            the font size
        """
        if self.font_size == font_size:
            return
        self.font_size = font_size
        font = QFont()
        font.setPointSize(font_size)
        self.setFont(font)
Пример #36
0
def test():
    import os.path as osp
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication(test_time=5)
    shell = ExternalSystemShell(wdir=osp.dirname(__file__),
                                light_background=False)

    app.aboutToQuit.connect(shell.finish_process)

    from qtpy.QtGui import QFont
    font = QFont()
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Пример #37
0
def tuple_to_qfont(tup):
    """
    Create a QFont from tuple:
        (family [string], size [int], italic [bool], bold [bool])
    """
    if not isinstance(tup, tuple) or len(tup) != 4 \
       or not font_is_installed(tup[0]) \
       or not isinstance(tup[1], int) \
       or not isinstance(tup[2], bool) \
       or not isinstance(tup[3], bool):
        return None
    font = QFont()
    family, size, italic, bold = tup
    font.setFamily(family)
    font.setPointSize(size)
    font.setItalic(italic)
    font.setBold(bold)
    return font
Пример #38
0
    def data(self, index, role=Qt.DisplayRole):
        """Override Qt method"""
        if not index.isValid() or not 0 <= index.row() < len(self._rows):
            return to_qvariant()
        row = index.row()
        column = index.column()

        # Carefull here with the order, this has to be adjusted manually
        if self._rows[row] == row:
            name, unlink, link, fetch = [u'', u'', u'', u'']
        else:
            name, unlink, link, fetch = self._rows[row]

        if role == Qt.DisplayRole:
            if column == 0:
                return to_qvariant(name)
            elif column == 1:
                return to_qvariant(unlink)
            elif column == 2:
                return to_qvariant(link)
            elif column == 3:
                return to_qvariant(fetch)
        elif role == Qt.TextAlignmentRole:
            if column in [0]:
                return to_qvariant(int(Qt.AlignLeft | Qt.AlignVCenter))
            elif column in [1, 2, 3]:
                return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
        elif role == Qt.ForegroundRole:
            return to_qvariant()
        elif role == Qt.FontRole:
            font = QFont()
            if row in self._bold_rows:
                font.setBold(True)
                return to_qvariant(font)
            else:
                font.setBold(False)
                return to_qvariant(font)
        return to_qvariant()
Пример #39
0
 def font(self, size):
     font = QFont(self.font_name)
     font.setPixelSize(size)
     return font
Пример #40
0
 def font(self, prefix, size):
     """Return a QFont corresponding to the given prefix and size."""
     font = QFont(self.fontname[prefix])
     font.setPixelSize(size)
     return font
Пример #41
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent=parent)

        self._shortcuts_summary_title = _("Spyder Keyboard ShortCuts")

        # Calculate font and amount of elements in each column according screen size
        width, height = self.get_screen_resolution()
        font_size = height / 80
        font_size = max(min(font_size, MAX_FONT_SIZE), MIN_FONT_SIZE)
        shortcuts_column = (height - 8 * font_size) / (font_size +16)

        # Widgets
        style = """
            QDialog {
              margin:0px;
              padding:0px;
              border-radius: 2px;
            }"""
        self.setStyleSheet(style)

        font_names = QFont()
        font_names.setPointSize(font_size)
        font_names.setBold(True)

        font_keystr = QFont()
        font_keystr.setPointSize(font_size)

        font_title = QFont()
        font_title.setPointSize(font_size+2)
        font_title.setBold(True)

        title_label = QLabel(self._shortcuts_summary_title)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setFont(font_title)

        # iter over shortcuts and create GroupBox for each context
        # with shortcuts in a grid

        columns_layout = QHBoxLayout()
        added_shortcuts = 0
        group = None
        # group shortcuts by context
        shortcuts = groupby(sorted(iter_shortcuts()), key=itemgetter(0))

        for context, group_shortcuts in shortcuts:
            for i, (context, name, keystr) in enumerate(group_shortcuts):
                # start of every column
                if added_shortcuts == 0:
                    column_layout = QVBoxLayout()

                # at start of new context add previous context group
                if i == 0 and added_shortcuts > 0:
                    column_layout.addWidget(group)

                # create group at start of column or context
                if added_shortcuts == 0 or i == 0:
                    if context == '_': context = 'Global'

                    group = QGroupBox(context.capitalize())
                    group.setFont(font_names)

                    group_layout = QGridLayout()
                    group.setLayout(group_layout)

                    # Count space for titles
                    added_shortcuts += 1

                # Widgets
                label_name = QLabel(name.capitalize().replace('_', ' '))
                label_name.setFont(font_names)

                keystr = QKeySequence(keystr).toString(QKeySequence.NativeText)
                label_keystr = QLabel(keystr)
                label_keystr.setFont(font_keystr)

                group_layout.addWidget(label_name, i, 0)
                group_layout.addWidget(label_keystr, i, 1)

                added_shortcuts += 1

                if added_shortcuts >= shortcuts_column:
                    column_layout.addWidget(group)
                    columns_layout.addLayout(column_layout)
                    added_shortcuts = 0

        column_layout.addWidget(group)
        column_layout.addStretch()  # avoid lasts sections to appear too big
        columns_layout.addLayout(column_layout)

        # Scroll widget
        self.scroll_widget = QWidget()
        self.scroll_widget.setLayout(columns_layout)
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidget(self.scroll_widget)

        # widget setup
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.95)

        # layout
        self._layout = QVBoxLayout()
        self._layout.addWidget(title_label)

        self._layout.addWidget(self.scroll_area)
        self.setLayout(self._layout)

        self.setGeometry(0, 0, width, height)
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not self.stats:
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(
                0, Qt.DisplayRole,
                _('No timings to display. '
                  'Did you forget to add @profile decorators ?')
                .format(url=WEBSITE_URL))
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for func_info, func_data in self.stats.items():
            # Function name and position
            filename, start_line_no, func_name = func_info
            func_stats, func_total_time = func_data
            func_item = QTreeWidgetItem(self)
            func_item.setData(
                0, Qt.DisplayRole,
                _('{func_name} ({time_ms:.3f}ms) in file "{filename}", '
                  'line {line_no}').format(
                    filename=filename,
                    line_no=start_line_no,
                    func_name=func_name,
                    time_ms=func_total_time * 1e3))
            func_item.setFirstColumnSpanned(True)
            func_item.setData(COL_POS, Qt.UserRole,
                              (osp.normpath(filename), start_line_no))

            # For sorting by time
            func_item.setData(COL_TIME, Qt.DisplayRole, func_total_time * 1e3)
            func_item.setData(COL_PERCENT, Qt.DisplayRole,
                              func_total_time * 1e3)

            if self.parent().use_colors:
                # Choose deteministic unique color for the function
                md5 = hashlib.md5((filename + func_name).encode("utf8")).hexdigest()
                hue = (int(md5[:2], 16) - 68) % 360  # avoid blue (unreadable)
                func_color = QColor.fromHsv(hue, 200, 255)
            else:
                # Red color only
                func_color = QColor.fromRgb(255, 0, 0)

            # Lines of code
            for line_info in func_stats:
                line_item = QTreeWidgetItem(func_item)
                (line_no, code_line, line_total_time, time_per_hit,
                 hits, percent) = line_info
                self.fill_item(
                    line_item, filename, line_no, code_line,
                    line_total_time, percent, time_per_hit, hits)

                # Color background
                if line_total_time is not None:
                    alpha = percent
                    color = QColor(func_color)
                    color.setAlphaF(alpha)  # Returns None
                    color = QBrush(color)
                    for col in range(self.columnCount()):
                        line_item.setBackground(col, color)
                else:

                    for col in range(self.columnCount()):
                        line_item.setForeground(col, CODE_NOT_RUN_COLOR)

                # Monospace font for code
                line_item.setFont(COL_LINE, monospace_font)
Пример #43
0
class TestDataModel(QAbstractItemModel):
    """
    Model class storing test results for display.

    Test results are stored as a list of TestResults in the property
    `self.testresults`. Every test is exposed as a child of the root node,
    with extra information as second-level nodes.

    As in every model, an iteem of data is identified by its index, which is
    a tuple (row, column, id). The id is TOPLEVEL_ID for top-level items.
    For level-2 items, the id is the index of the test in `self.testresults`.

    Signals
    -------
    sig_summary(str)
       Emitted with new summary if test results change.
    """

    sig_summary = Signal(str)

    def __init__(self, parent=None):
        """Constructor."""
        QAbstractItemModel.__init__(self, parent)
        self.abbreviator = Abbreviator()
        self.testresults = []
        try:
            self.monospace_font = parent.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            self.monospace_font = QFont("Courier New")
            self.monospace_font.setPointSize(10)

    @property
    def testresults(self):
        """List of test results."""
        return self._testresults

    @testresults.setter
    def testresults(self, new_value):
        """Setter for test results."""
        self.beginResetModel()
        self.abbreviator = Abbreviator(res.name for res in new_value)
        self._testresults = new_value
        self.endResetModel()
        self.emit_summary()

    def add_testresults(self, new_tests):
        """
        Add new test results to the model.

        Arguments
        ---------
        new_tests : list of TestResult
        """
        firstRow = len(self.testresults)
        lastRow = firstRow + len(new_tests) - 1
        for test in new_tests:
            self.abbreviator.add(test.name)
        self.beginInsertRows(QModelIndex(), firstRow, lastRow)
        self.testresults.extend(new_tests)
        self.endInsertRows()
        self.emit_summary()

    def update_testresults(self, new_results):
        """
        Update some test results by new results.

        The tests in `new_results` should already be included in
        `self.testresults` (otherwise a `KeyError` is raised). This function
        replaces the existing results by `new_results`.

        Arguments
        ---------
        new_results: list of TestResult
        """
        idx_min = idx_max = None
        for new_result in new_results:
            for (idx, old_result) in enumerate(self.testresults):
                if old_result.name == new_result.name:
                    self.testresults[idx] = new_result
                    if idx_min is None:
                        idx_min = idx_max = idx
                    else:
                        idx_min = min(idx_min, idx)
                        idx_max = max(idx_max, idx)
                    break
            else:
                raise KeyError('test not found')
        if idx_min is not None:
            self.dataChanged.emit(self.index(idx_min, 0),
                                  self.index(idx_max, len(HEADERS) - 1))
            self.emit_summary()

    def index(self, row, column, parent=QModelIndex()):
        """
        Construct index to given item of data.

        If `parent` not valid, then the item of data is on the top level.
        """
        if not self.hasIndex(row, column, parent):  # check bounds etc.
            return QModelIndex()
        if not parent.isValid():
            return self.createIndex(row, column, TOPLEVEL_ID)
        else:
            testresult_index = parent.row()
            return self.createIndex(row, column, testresult_index)

    def data(self, index, role):
        """
        Return data in `role` for item of data that `index` points to.

        If `role` is `DisplayRole`, then return string to display.
        If `role` is `TooltipRole`, then return string for tool tip.
        If `role` is `FontRole`, then return monospace font for level-2 items.
        If `role` is `BackgroundRole`, then return background color.
        If `role` is `TextAlignmentRole`, then return right-aligned for time.
        If `role` is `UserRole`, then return location of test as (file, line).
        """
        if not index.isValid():
            return None
        row = index.row()
        column = index.column()
        id = index.internalId()
        if role == Qt.DisplayRole:
            if id != TOPLEVEL_ID:
                return self.testresults[id].extra_text[index.row()]
            elif column == STATUS_COLUMN:
                return self.testresults[row].status
            elif column == NAME_COLUMN:
                return self.abbreviator.abbreviate(self.testresults[row].name)
            elif column == MESSAGE_COLUMN:
                return self.testresults[row].message
            elif column == TIME_COLUMN:
                time = self.testresults[row].time
                return '' if time is None else '{:.2f}'.format(time * 1e3)
        elif role == Qt.ToolTipRole:
            if id == TOPLEVEL_ID and column == NAME_COLUMN:
                return self.testresults[row].name
        elif role == Qt.FontRole:
            if id != TOPLEVEL_ID:
                return self.monospace_font
        elif role == Qt.BackgroundRole:
            if id == TOPLEVEL_ID:
                testresult = self.testresults[row]
                return COLORS[testresult.category]
        elif role == Qt.TextAlignmentRole:
            if id == TOPLEVEL_ID and column == TIME_COLUMN:
                return Qt.AlignRight
        elif role == Qt.UserRole:
            if id == TOPLEVEL_ID:
                testresult = self.testresults[row]
                return (testresult.filename, testresult.lineno)
        else:
            return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """Return data for specified header."""
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return HEADERS[section]
        else:
            return None

    def parent(self, index):
        """Return index to parent of item that `index` points to."""
        if not index.isValid():
            return QModelIndex()
        id = index.internalId()
        if id == TOPLEVEL_ID:
            return QModelIndex()
        else:
            return self.index(id, 0)

    def rowCount(self, parent=QModelIndex()):
        """Return number of rows underneath `parent`."""
        if not parent.isValid():
            return len(self.testresults)
        if parent.internalId() == TOPLEVEL_ID and parent.column() == 0:
            return len(self.testresults[parent.row()].extra_text)
        return 0

    def columnCount(self, parent=QModelIndex()):
        """Return number of rcolumns underneath `parent`."""
        if not parent.isValid():
            return len(HEADERS)
        else:
            return 1

    def sort(self, column, order):
        """Sort model by `column` in `order`."""
        def key_time(result):
            return result.time or -1

        self.beginResetModel()
        reverse = order == Qt.DescendingOrder
        if column == STATUS_COLUMN:
            self.testresults.sort(key=attrgetter('category', 'status'),
                                  reverse=reverse)
        elif column == NAME_COLUMN:
            self.testresults.sort(key=attrgetter('name'), reverse=reverse)
        elif column == MESSAGE_COLUMN:
            self.testresults.sort(key=attrgetter('message'), reverse=reverse)
        elif column == TIME_COLUMN:
            self.testresults.sort(key=key_time, reverse=reverse)
        self.endResetModel()

    def summary(self):
        """Return summary for current results."""
        def n_test_or_tests(n):
            test_or_tests = _('test') if n == 1 else _('tests')
            return '{} {}'.format(n, test_or_tests)

        if not len(self.testresults):
            return _('No results to show.')
        counts = Counter(res.category for res in self.testresults)
        if all(counts[cat] == 0
               for cat in (Category.FAIL, Category.OK, Category.SKIP)):
            txt = n_test_or_tests(counts[Category.PENDING])
            return _('collected {}').format(txt)
        msg = _('{} failed').format(n_test_or_tests(counts[Category.FAIL]))
        msg += _(', {} passed').format(counts[Category.OK])
        if counts[Category.SKIP]:
            msg += _(', {} other').format(counts[Category.SKIP])
        if counts[Category.PENDING]:
            msg += _(', {} pending').format(counts[Category.PENDING])
        return msg

    def emit_summary(self):
        """Emit sig_summary with summary for current results."""
        self.sig_summary.emit(self.summary())
Пример #44
0
    def initialize_editor(self):



        self.editor = QsciScintilla()

#        self.editor.cursorPositionChanged.connect(self.e)
#        self.editor.copyAvailable.connect(self.e)
#        self.editor.indicatorClicked.connect(self.e)
#        self.editor.indicatorReleased.connect(self.e)
#        self.editor.linesChanged.connect(self.e)
#        self.editor.marginClicked.connect(self.e)
#        self.editor.modificationAttempted.connect(self.e)
#        self.editor.modificationChanged.connect(self.e)
#        self.editor.selectionChanged.connect(self.e)
#        self.editor.textChanged.connect(self.e)
#        self.editor.userListActivated.connect(self.e)

        if self.editor.__class__.__name__ == "LineTextWidget":
            return  # When using PySide without QSciScintilla

        # define the font to use
        font = QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        fm = QFontMetrics(font)

        # set the default font of the self.editor
        # and take the same font for line numbers
        self.editor.setFont(font)
        self.editor.setMarginsFont(font)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.editor.setMarginWidth(0, fm.width("00000") + 5)
        self.editor.setMarginLineNumbers(0, True)

        self.editor.setTabWidth(4)

        # Folding visual : we will use boxes
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        self.editor.setAutoIndent(True)

        # Braces matching
        self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Editing line color
        self.editor.setCaretLineVisible(True)
        self.editor.setCaretLineBackgroundColor(QColor("#CDA869"))

        # Margins colors
        # line numbers margin
        self.editor.setMarginsBackgroundColor(QColor("#333333"))
        self.editor.setMarginsForegroundColor(QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        self.editor.setFoldMarginColors(QColor("#99CC66"), QColor("#333300"))

        # Choose a lexer
        self.lexer = QsciLexerPython()
        self.lexer.setDefaultFont(font)

        # Set the length of the string before the editor tries to autocomplete
        # In practise this would be higher than 1
        # But its set lower here to make the autocompletion more obvious
        self.editor.setAutoCompletionThreshold(1)
        # Tell the editor we are using a QsciAPI for the autocompletion
        self.editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.editor.setLexer(self.lexer)
        self.editor.setCallTipsStyle(QsciScintilla.CallTipsContext)

        # self.editor.setCallTipsVisible(0)
        # Create an API for us to populate with our autocomplete terms
        self.api = QsciAPIs(self.lexer)

        # Compile the api for use in the lexer
        self.api.prepare()
Пример #45
0
    def __init__(self, hub, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.hub = hub

        self.wave_range = (None, None)

        loadUi(os.path.join(os.path.dirname(__file__), "ui", "linelists_window.ui"), self)

        # QtDesigner can't add a combo box to a tool bar...
        self.line_list_selector = QComboBox()
        self.line_list_selector.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.line_list_selector.setMinimumWidth(230)
        self.line_list_selector.setToolTip("Select line list from internal library")
        self.main_toolbar.addWidget(self.line_list_selector)

        # QtDesigner creates tabbed widgets with 2 tabs, and doesn't allow
        # removing then in the designer itself. Remove in here then.
        while self.tab_widget.count() > 0:
            self.tab_widget.removeTab(0)

        # Local references for often used objects.
        self.plot_window = self.hub.plot_window

        # Request that line lists be read from wherever are they sources.
        if not hasattr(self, 'linelists'):
            self._request_linelists()

            # Populate line list selector with internal line lists
            model = self.line_list_selector.model()
            item = QStandardItem("Select line list")
            font = QFont("Monospace")
            font.setStyleHint(QFont.TypeWriter)
            font.setPointSize(12)
            item.setFont(font)
            model.appendRow(item)
            for description in linelist.descriptions():
                item = QStandardItem(str(description))
                item.setFont(font)
                model.appendRow(item)

        self.line_labels_plotter = LineLabelsPlotter(self)

        # Connect controls to appropriate signals.

        self.draw_button.clicked.connect(
            lambda:self.line_labels_plotter._plot_linelists(
            table_views=self._get_table_views(),
            panes=self._get_panes(),
            units=self.hub.plot_widget.spectral_axis_unit,
            caller=self.line_labels_plotter))

        self.erase_button.clicked.connect(lambda:self.erase_linelabels.emit(self.plot_window.plot_widget))
        self.dismiss_button.clicked.connect(self.dismiss_linelists_window.emit)

        self.actionOpen.triggered.connect(lambda:self._open_linelist_file(file_name=None))
        self.actionExport.triggered.connect(lambda:self._export_to_file(file_name=None))
        self.line_list_selector.currentIndexChanged.connect(self._lineList_selection_change)
        self.tab_widget.tabCloseRequested.connect(self._on_tab_close)

        self.hub.plot_window.window_removed.connect(self.dismiss_linelists_window.emit)