def setup_editor(self):
        variable_format = QTextCharFormat()
        variable_format.setFontWeight(QFont.Bold)
        variable_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[A-Z_]+\\b", variable_format)

        single_line_comment_format = QTextCharFormat()
        single_line_comment_format.setBackground(QColor("#77ff77"))
        self._highlighter.add_mapping("#[^\n]*", single_line_comment_format)

        quotation_format = QTextCharFormat()
        quotation_format.setBackground(Qt.cyan)
        quotation_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\".*\"", quotation_format)

        function_format = QTextCharFormat()
        function_format.setFontItalic(True)
        function_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[a-z0-9_]+\\(.*\\)", function_format)

        font = QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self._editor = QPlainTextEdit()
        self._editor.setFont(font)
        self._highlighter.setDocument(self._editor.document())
Beispiel #2
0
    def _create_style(self):
        self.setWindowFlags(Qt.Window)
        self.setWindowTitle('Test in Maya')
        self.setStyleSheet('font-size: 12pt')

        screen = QApplication.primaryScreen()
        size = screen.size() * 0.66
        self.resize(size)

        self.text_edit.setReadOnly(True)
        self.text_edit.setStyleSheet('QTextEdit:focus{ border: none; }')

        font = QFont("Consolas, 'Courier New', monospace")
        font.setFixedPitch(True)
        self.text_edit.setFont(font)
Beispiel #3
0
    def __init__(self, parent, log_name):
        super(DlgLog, self).__init__(parent)
        self.ui = Ui_DlgLog()
        self.ui.setupUi(self)

        font = QFont()
        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.ui.txtEdit.setCurrentFont(font)

        # opens the log file
        with open(log_name, 'r') as f:
            str_res = f.read()
            # puts the content to text box
            self.ui.txtEdit.setPlainText(str_res)
Beispiel #4
0
    def _set_font(self):
        mono_font = QFont("monospace")
        mono_font.setStyleStrategy(QFont.ForceIntegerMetrics)
        mono_font.setFixedPitch(True)
        mono_font.setPointSize(9)

        font_metrics = QFontMetrics(mono_font)

        self.font_width = font_metrics.width("M")

        self.setFont(mono_font)
        self.layout.setFont(mono_font)
        self.viewport().setFont(mono_font)

        self.line_height = self.fontMetrics().height()

        self.viewport().update()
Beispiel #5
0
    def ui_setup(self):
        self._widget = QWidget()
        self._help_edit = QTextEdit()

        text_font = QFont()
        text_font.setFixedPitch(True)
        text_font.setFamily('monospace')

        style = 'color: rgb(6, 117, 0);' \
                'background-color: rgb(230, 255, 230);' \
                'border: no-border;'

        self._help_edit.setFont(text_font)
        self._help_edit.setStyleSheet(style)
        self._help_edit.setText(self.text)

        main_layout = QGridLayout()
        main_layout.addWidget(self._help_edit, 0, 0, 1, 1)

        self._widget.setLayout(main_layout)
Beispiel #6
0
class QtPythonEditor(QPlainTextEdit):

    HIGHLIGHT_COLOR = Qt.lightGray
    HIGHLIGHTER_CLASS = QtPythonHighlighter

    DEFAULT_FONT_FAMILY = "Courier"
    DEFAULT_FONT_SIZE = 10
    DEFAULT_LINE_WRAP_MODE = QPlainTextEdit.NoWrap

    TAB_STOP = 4

    _font = None
    _font_size = DEFAULT_FONT_SIZE

    def __init__(self, parent=None):

        QPlainTextEdit.__init__(self, parent)

        self._highlighter = self.HIGHLIGHTER_CLASS(self.document())
        self._line_number_widget = QtLineNumberArea(self)
        self.setLineWrapMode(self.DEFAULT_LINE_WRAP_MODE)

        self._initTextAttrs()
        self._initEvents()

    def _initEvents(self):

        self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
        self.updateRequest.connect(self.updateLineNumberArea)
        #self.cursorPositionChanged.connect(self.highlightCurrentLine)

        self.updateLineNumberAreaWidth()

    def _initTextAttrs(self):

        self.font = QFont()
        self.font.setFamily(self.DEFAULT_FONT_FAMILY)
        self.font.setStyleHint(QFont.Monospace)
        self.font.setFixedPitch(True)
        self.font.setPointSize(self._font_size)

        self.setFont(self.font)
        self.setTabStopWidth(self.TAB_STOP *
                             QFontMetrics(self.font).width(" "))

    def resizeEvent(self, event):

        super(QtPythonEditor, self).resizeEvent(event)

        cr = self.contentsRect()
        self._line_number_widget.setGeometry(
            QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(),
                  cr.height()))

    def eventFilter(self, obj, event):
        """
        Implemented here to enable standard text editor ctrl+scroll_wheel text zooming
        """

        if event.type() == QEvent.Wheel:
            if event.modifiers() == Qt.ControlModifier:
                if event.delta() > 0:
                    self._font_size = max(self._font_size - 2,
                                          self.DEFAULT_FONT_SIZE)
                    #self.zoomIn(2)
                else:
                    self._font_size = max(self._font_size + 2,
                                          self.DEFAULT_FONT_SIZE)
                    #self.zoomOut(2)

                self.font.setPointSize(self._font_size)
                self.setFont(self.font)
                self.setTabStopWidth(self.TAB_STOP *
                                     QFontMetrics(self.font).width(" "))

                return True

        return False

    def lineNumberAreaWidth(self):

        digits = 1
        count = max(1, self.blockCount())
        while count >= 10:
            count /= 10
            digits += 1
        space = 3 + self.fontMetrics().width("9") * digits

        return space

    def updateLineNumberArea(self, rect, dy):

        if dy:
            self._line_number_widget.scroll(0, dy)
        else:
            self._line_number_widget.update(0, rect.y(),
                                            self._line_number_widget.width(),
                                            rect.height())

        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth()

    def updateLineNumberAreaWidth(self):

        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

    def highlightCurrentLine(self):

        extraSelections = []

        if not self.isReadOnly():
            selection = QTextEdit.ExtraSelection()

            lineColor = QColor(self.HIGHLIGHT_COLOR).lighter(160)

            selection.format.setBackground(lineColor)
            selection.format.setProperty(QTextFormat.FullWidthSelection, True)
            selection.cursor = self.textCursor()
            selection.cursor.clearSelection()
            extraSelections.append(selection)

        self.setExtraSelections(extraSelections)

    def lineNumberAreaPaintEvent(self, event):

        mypainter = QPainter(self._line_number_widget)

        mypainter.fillRect(event.rect(), Qt.lightGray)

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = self.blockBoundingGeometry(block).translated(
            self.contentOffset()).top()
        bottom = top + self.blockBoundingRect(block).height()

        # Just to make sure I use the right font
        height = self.fontMetrics().height()
        while block.isValid() and (top <= event.rect().bottom()):
            if block.isVisible() and (bottom >= event.rect().top()):
                number = str(blockNumber + 1)
                mypainter.setPen(Qt.black)
                mypainter.drawText(0, top, self._line_number_widget.width(),
                                   height, Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
            blockNumber += 1

    def getHighlighter(self):

        return self._highlighter

    def setFontSize(self, size):

        font = self.font()
        font.setPointSize(size)
        self.setFont(font)
Beispiel #7
0
class SequenceRecordsWindow(QWidget):
    def __init__(self, parent):
        super(SequenceRecordsWindow, self).__init__(parent)
        self.grid_layout = QGridLayout()
        self.grid_layout.setContentsMargins(0, 0, 0, 0)
        self.grid_layout.setSpacing(0)
        self.setLayout(self.grid_layout)

        self.seq_font = QFont()
        self.seq_font.setFamily("Noto Sans Mono")
        self.seq_font.setPointSize(12)
        self.seq_font.setFixedPitch(True)
        self.seq_font.setStyleHint(QFont.Monospace)

        self.seq_h_scroll_bar = QScrollBar(self, self.parent())
        self.seq_h_scroll_bar.setOrientation(Qt.Horizontal)
        self.seq_h_scroll_bar.setMinimum(0)
        self.seq_h_scroll_bar.setMaximum(self.longest_seq_len - self.char_nb)
        self.seq_h_scroll_bar.valueChanged.connect(self.move_seqs)
        self.grid_layout.addWidget(self.seq_h_scroll_bar,
                                   self.grid_layout.rowCount(), 5)

        self.lower_spacer_item = QSpacerItem(1, 1, QSizePolicy.Minimum,
                                             QSizePolicy.MinimumExpanding)
        self.grid_layout.addItem(self.lower_spacer_item)

        self.seq_record_items = []

    def sizeHint(self):  # Workaroud QTBUG-70305
        return self.parent().parent().size()

    def populate(self, seq_records):
        self.grid_layout.removeWidget(self.seq_h_scroll_bar)
        self.grid_layout.removeItem(self.lower_spacer_item)

        for seq_record in seq_records:
            new_row = self.grid_layout.rowCount()
            self.seq_record_items.append(
                SequenceRecordItem(self, seq_record, self.seq_font))
            for widget_index in range(0,
                                      len(self.seq_record_items[-1].widgets)):
                col = widget_index
                self.seq_record_items[-1].seqLabel.installEventFilter(self)
                self.grid_layout.addWidget(
                    self.seq_record_items[-1].widgets[widget_index], new_row,
                    col)

            if len(seq_record) > self.longest_seq_len:
                self.longest_seq_len = len(seq_record)

        self.update_char_nb()
        self.grid_layout.addWidget(self.seq_h_scroll_bar,
                                   self.grid_layout.rowCount(), 5)
        self.grid_layout.addItem(self.lower_spacer_item)
        self.display_all_seq()

    def clear(self):
        # TODO
        pass

    def eventFilter(self, watched, event):
        if event.type() == QEvent.Resize:
            self.update_char_nb()
            self.update_scrollbar()
            self.display_all_seq()
        return super(SequenceRecordsWindow, self).eventFilter(watched, event)

    def display_all_seq(self):
        for seq_record_item in self.seq_record_items:
            seq_record_item.seqLabel.display_seq(
                seq_record_item.seq_record.seq, self.display_begin,
                self.char_nb)

    def update_char_nb(self):
        font_metrics = QFontMetrics(self.seq_font)
        px_wide_char = font_metrics.width("A")
        label_width = self.seq_record_items[0].seqLabel.width(
        )  # width of first seq label = all seq labels
        approx_char_nb = label_width // px_wide_char

        test_str = "A" * approx_char_nb

        while font_metrics.width(
                test_str) < label_width:  # fontMetrics not precise at all...
            test_str += "A"

        while font_metrics.width(
                test_str) >= label_width:  # fontMetrics not precise at all...
            test_str = test_str[:-1]

        self.char_nb = len(test_str)

    def update_scrollbar(self):
        self.seq_h_scroll_bar.setMaximum(self.longest_seq_len - self.char_nb +
                                         12)

    def move_seqs(self, value):
        print(value)
        self.display_begin = value
        self.display_all_seq()

    char_nb = 0
    longest_seq_len = 0
    display_begin = 0
    def __init__(self, parent, task):
        '''
        Params:
        -------
        parent: FrmMainWindow
        task : MirrorTask
        '''
        super(DlgPending, self).__init__(parent)

        # init UI
        self.ui = Ui_dlgPendng()
        self.ui.setupUi(self)
        # removes the help button
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint
                            | Qt.WindowCloseButtonHint)

        # connect slots
        self.ui.btnOK.clicked.connect(lambda: self.Btn_Clicked(self.ui.btnOK))
        self.ui.btnCancel.clicked.connect(
            lambda: self.Btn_Clicked(self.ui.btnCancel))
        # get task params
        cmd, src, dst = task.GetParams()
        # append '/l' switch
        cmd.append('/l')
        # prepare subprocess
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        # get output of result
        stdout = proc.communicate()[0].decode('utf-8')
        str_msg = stdout

        # make font so each character's width is same
        font = QFont()
        font.setFamily("Courier")
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.ui.textEdit.setCurrentFont(font)
        self.ui.textEdit.setText(str_msg)

        # parse the pending result
        # ex: dirs[1,5,0] means 1 out of 5
        info = {'dirs': [], 'files': [], 'bytes': []}
        try:
            # split each line
            for line in stdout.split('\r\n'):
                # if current line is for directory
                if 'Dirs :' in line:
                    tmp = [
                        a for a in line.split(':')[1].split('  ') if len(a) > 0
                    ]  # noqa
                    if len(tmp) == 6:
                        info['dirs'] = tmp
                # if current line is for files
                elif 'Files :' in line:
                    tmp = [
                        a for a in line.split(':')[1].split('  ') if len(a) > 0
                    ]  # noqa
                    if len(tmp) == 6:
                        info['files'] = tmp
                # if current line is for bytes
                elif 'Bytes :' in line:
                    tmp = [
                        a for a in line.split(':')[1].split('  ') if len(a) > 0
                    ]  # noqa
                    if len(tmp) == 6:
                        info['bytes'] = tmp
            # check out pending result is valid
            if len(info['dirs']) == 0:
                self.ui.btnOK.setEnabled(False)
                return
            # sets the anaylsis numbers
            # dir copy
            self.ui.lbl_copyFolder.setText(
                f"{info['dirs'][1]} out of {info['dirs'][0]}")
            # dir del
            self.ui.lbl_delFolders.setText(f"{info['dirs'][5]}")
            # file copy
            self.ui.lbl_copyFile.setText(
                f"{info['files'][1]} out of {info['files'][0]}")
            # dir del
            self.ui.lbl_delFile.setText(f"{info['files'][5]}")
            # bytes copy
            self.ui.lbl_copyBytes.setText(
                f"{info['bytes'][1]}bytes out of {info['bytes'][0]}bytes")
            # bytes del
            self.ui.lbl_delBytes.setText(f"{info['bytes'][5]}bytes")
        except Exception as e:
            print(f'Pending dlg err:{e}')