Beispiel #1
0
    def __init__(self, result, type, parent=None):
        super(ResultBlock, self).__init__(parent)
        self.result = result

        self.text_font = QFont('monospace', 16)

        if type == 'plain':
            self.result_block = QTextEdit()
            self.result_block.setFont(self.text_font)
            self.result_block.insertPlainText(result)
            self.result_block.setMinimumHeight(600)

            # Make sure scrollbar is always at the top
            self.result_block.moveCursor(QTextCursor().Start)
            self.result_block.ensureCursorVisible()

            self.result_block.setReadOnly(True)

        elif type == 'html':
            self.result_block = QTextEdit()
            self.result_block.setFont(self.text_font)
            self.result_block.insertHtml(result)
            self.result_block.setMinimumHeight(600)

            # Make sure scrollbar is always at the top
            self.result_block.moveCursor(QTextCursor().Start)
            self.result_block.ensureCursorVisible()

            self.result_block.setReadOnly(True)

        elif type == 'image':
            self.result_block = QScrollArea()

            self.image_preview = QWidget()
            image_preview_layout = QVBoxLayout()
            image_preview_layout.addWidget(result)
            print(result)
            self.image_preview.setLayout(image_preview_layout)

            self.result_block.setWidget(self.image_preview)
            self.result_block.setWidgetResizable(True)
            self.result_block.setMinimumHeight(600)

        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.result_block)

        # Set layout
        self.setLayout(layout)
Beispiel #2
0
    def getFirstVisibleBlockId(self):
        """
        Detect the first block for which bounding rect - once translated in absolute coordinated -
        is contained by the editor's text area
        :return: the first visible block
        """

        if self.verticalScrollBar().sliderPosition() == 0:
            return 0

        cursor = QTextCursor(self.document())
        cursor.movePosition(QTextCursor.Start)
        for i in range(self.document().blockCount()):
            block = cursor.block()
            r1 = self.viewport().geometry()
            r2 = self.document().documentLayout().blockBoundingRect(block).translated(
                self.viewport().geometry().x(),
                self.viewport().geometry().y() - self.verticalScrollBar().sliderPosition()
            ).toRect()

            if r1.contains(r2, True):
                return i

            cursor.movePosition(QTextCursor.NextBlock)

        return 0
    def update_visuals(self):
        """
        Moves text editor's cursor to match currently highlighted `find` word, performs `find` highlighting,
        indicates index on dialog.
        """
        # x of y words indicator
        idx = self.found_cursors.index(self.current_cursor) + 1
        self.found_info_label.setText("{} of {} matches".format(
            idx, len(self.found_cursors)))
        self.found_info_label.repaint()

        # move along text editor's viewport
        next_pte_cursor = QTextCursor(self.current_cursor)
        next_pte_cursor.clearSelection()
        self.plain_text_edit.setTextCursor(next_pte_cursor)

        #highlighting
        normal_color = QColor(Qt.yellow).lighter()
        current_color = QColor(Qt.magenta).lighter()
        extra_selections: List[QTextEdit.ExtraSelection] = []
        for cur in self.found_cursors:
            selection = QTextEdit.ExtraSelection()
            selection.cursor = cur
            if cur == self.current_cursor:
                selection.format.setBackground(current_color)
            else:
                selection.format.setBackground(normal_color)
            extra_selections.append(selection)
        self.plain_text_edit.setExtraSelections(extra_selections)
    def build_invoice(self, data):
        document = QTextDocument()
        self.setDocument(document)
        document.setPageSize(QSizeF(self.doc_width, self.doc_height))
        document.setDefaultFont(font)
        cursor = QTextCursor(document)
        cursor.insertText(f"Customer Name: {data['c_name']}\n")
        cursor.insertText(f"Customer Address: {data['c_addr']}\n")
        cursor.insertText(f"Date: {data['i_date']}\n")
        cursor.insertText(f"Total Due: {data['total_due']}\n")
# +        
        return document                                                         # +++
Beispiel #5
0
    def textUnderCursor(self):
        tc = self.textCursor()
        tc.select(QTextCursor.WordUnderCursor)

        selected_text = tc.selectedText()

        if selected_text == "(":
            cursor_pos = tc.position()
            if cursor_pos - 2 > 0:
                cursor_prev = QTextCursor(self.document())
                cursor_prev.setPosition(cursor_pos - 2)
                cursor_prev.select(QTextCursor.WordUnderCursor)
                selected_text = cursor_prev.selectedText()

        #print(selected_text)
        return selected_text
Beispiel #6
0
 def init_ui(self):
     layout = QVBoxLayout(self.central_widget)
     layout.addWidget(self.text_editor)
     help_button = QPushButton('Помощь по синтаксису')
     help_button.clicked.connect(self.help_syntax)
     layout.addWidget(help_button)
     save_button = QPushButton('Сохранить изменения')
     save_button.setStyleSheet('font-weight: bold;')
     save_button.clicked.connect(self.save_module)
     layout.addWidget(save_button)
     save_as_button = QPushButton('Сохранить как ...')
     save_as_button.setStyleSheet('font-style: italic;')
     save_as_button.clicked.connect(self.save_as_module)
     layout.addWidget(save_as_button)
     cursor = QTextCursor(self.text_editor.document())
     cursor.movePosition(QTextCursor.End)
     self.text_editor.setTextCursor(cursor)
     self.setCentralWidget(self.central_widget)
    def find_all(
        text: str, document: QTextDocument, flags=QTextDocument.FindFlags()
    ) -> List[QTextCursor]:
        """
        Finds all occurrences of `text` in `document`, in order.

        :param text: Text to find.
        :param document: Document to search.
        :param flags: Conditions to set on the search: none or (whole word and/or match case)
        :return: Ordered list of all found instances.
        """
        cursor = QTextCursor(document)  # default pos == 0
        found: List[QTextCursor] = []

        while True:
            cursor = document.find(text, cursor, flags)
            if cursor.isNull():
                return found
            else:
                found.append(cursor)
 def init_ui(self):
     layout = QVBoxLayout(self.central_widget)
     layout.addWidget(self.text_editor)
     help_button = QPushButton('Помощь по синтаксису')
     help_button.clicked.connect(self.help_syntax)
     layout.addWidget(help_button)
     crypto_label = QLabel('Алгоритм шифрования')
     crypto_label.setStyleSheet('font-style: italic;')
     crypto_label.setAlignment(Qt.AlignCenter)
     layout.addWidget(crypto_label)
     self.type_of_crypto.addItem('XOR')
     self.type_of_crypto.addItem('AES-256')
     layout.addWidget(self.type_of_crypto)
     create_button = QPushButton('Сохранить модуль')
     create_button.setStyleSheet('font-weight: bold;')
     create_button.clicked.connect(self.save_module)
     layout.addWidget(create_button)
     self.text_editor.setText(create_basic_text())
     cursor = QTextCursor(self.text_editor.document())
     cursor.movePosition(QTextCursor.End)
     self.text_editor.setTextCursor(cursor)
     self.setCentralWidget(self.central_widget)
Beispiel #9
0
    def replace_patterns(self, code):

        # clear format
        fmt = QTextCharFormat()
        fmt.setBackground(QColor('#2b2b2b'))

        cursor = QTextCursor(self.document())
        cursor.setPosition(0, QTextCursor.MoveAnchor)
        cursor.setPosition(len(code) - 1, QTextCursor.KeepAnchor)
        self.just_changed_text = True
        cursor.setCharFormat(fmt)

        # static elements
        color = QColor(255, 255, 0, 50)

        for pattern in self.static_elements:
            positions = [
                i for i in range(len(code)) if code.startswith(pattern, i)
            ]
            for occ in reversed(positions):
                fmt.setBackground(color)
                cursor.setPosition(occ, QTextCursor.MoveAnchor)
                cursor.setPosition(occ + len(pattern), QTextCursor.KeepAnchor)
                self.just_changed_text = True
                cursor.setCharFormat(fmt)

        # usable components
        color = QColor(100, 100, 255, 200)

        for pattern in self.components:
            positions = [
                i for i in range(len(code)) if code.startswith(pattern, i)
            ]
            for occ in reversed(positions):
                fmt.setBackground(color)
                cursor.setPosition(occ, QTextCursor.MoveAnchor)
                cursor.setPosition(occ + len(pattern), QTextCursor.KeepAnchor)
                self.just_changed_text = True
                cursor.setCharFormat(fmt)
Beispiel #10
0
 def _highlight(self, editor: QTextEdit, text: str, fmt: QTextCharFormat,
                fmt_chg: QTextCharFormat):
     cursor = QTextCursor(editor.textCursor())
     if text.endswith('\n'):
         text = text[:-1]
     elif text.endswith('\n\1'):
         text = text[:-2] + '\1'
     pos_list = self._get_pos_list(text)
     text = text.replace('\0+',
                         '').replace('\0-',
                                     '').replace('\0^',
                                                 '').replace('\1', '')
     editor.setPlainText(text)
     n = 0
     for tag, start, end in pos_list:
         if not end == start + 2:
             cursor.setPosition(start - n)
             cursor.setPosition(end - n - 2, QTextCursor.KeepAnchor)
             if tag == '^':
                 cursor.mergeCharFormat(fmt_chg)
             else:
                 cursor.mergeCharFormat(fmt)
         n += 3
Beispiel #11
0
 def scroll_to_first_location(self):
     cursor = self.document().find(self._search_term)
     if not cursor.isNull():
         self.setTextCursor(cursor)
         self.ensureCursorVisible()
         self.setTextCursor(QTextCursor())