Ejemplo n.º 1
0
 def menu_about_static_sources(self):
     from PySide2.QtGui import QTextDocument
     self.dialog = TextAboutDialog('About Data')
     doc = QTextDocument()
     doc.setMarkdown(self._read_file('static_data/DATA_SOURCES.md'))
     self.dialog.ui.textEdit.setDocument(doc)
     self.dialog.show()
Ejemplo n.º 2
0
 def menu_about_app(self):
     from PySide2.QtGui import QTextDocument
     self.dialog = TextAboutDialog('About')
     doc = QTextDocument()
     doc.setMarkdown(self._read_file('README.md'))
     self.dialog.ui.textEdit.setDocument(doc)
     self.dialog.show()
Ejemplo n.º 3
0
    def __init__(self,
                 addr: int,
                 obj: QBlockCodeObj,
                 config: ConfigurationManager,
                 disasm_view: 'QDisassemblyBaseControl',
                 workspace: 'Workspace',
                 infodock: InfoDock,
                 parent: Any = None):
        super().__init__(parent=parent)
        self.addr = addr
        self._addr_str = "%08x" % self.addr
        self._addr_item: QGraphicsSimpleTextItem = None
        self.obj = obj
        self._width = 0
        self._height = 0
        self._config = config
        self.parent = parent
        self.workspace = workspace
        self.infodock = infodock
        self._disasm_view = disasm_view
        self._qtextdoc = QTextDocument()
        self._qtextdoc.setDefaultFont(self._config.disasm_font)
        self._qtextdoc.setDocumentMargin(0)

        self._addr_item = QGraphicsSimpleTextItem(self._addr_str, self)
        self._addr_item.setBrush(Conf.disasm_view_node_address_color)
        self._addr_item.setFont(Conf.disasm_font)

        self.update_document()
        self.setToolTip("Address: " + self._addr_str)

        self.refresh()
Ejemplo n.º 4
0
class TextDocument(Document, name="Text"):
    def __init__(self, path=None):
        super().__init__(path)

        self._document = QTextDocument()

    def document(self):
        return self._document

    @staticmethod
    def detectTypeFromName(name: str):
        return PurePath(name).suffix in [".txt", ".log"]

    @staticmethod
    def detectTypeFromSample(sample):
        try:
            sample.decode()
        except (UnicodeDecodeError, AttributeError):
            return False

        return True

    def reload(self):
        with self.path().open("r") as f:
            self._document.setPlainText(f.read())
Ejemplo n.º 5
0
 def testWrite(self):
     temporaryFile = QTemporaryFile(QDir.tempPath() + "/pdfwriter_test_XXXXXX.pdf")
     self.assertTrue(temporaryFile.open())
     pdfWriter = QPdfWriter(temporaryFile)
     pdfWriter.setPageLayout(QPageLayout(QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(10, 10, 10, 10)))
     doc = QTextDocument("Some text")
     doc.print_(pdfWriter)
     temporaryFile.close()
     self.assertTrue(temporaryFile.size() > 0)
Ejemplo n.º 6
0
 def sizeHint(self, option, index):
     transaction_type = index.data(Qt.DisplayRole)
     fontMetrics = option.fontMetrics
     document = QTextDocument("W")
     option.font.setWeight(QFont.Bold)
     document.setDefaultFont(option.font)
     w = document.idealWidth()
     h = fontMetrics.height()
     if (transaction_type
             == TransactionType.Dividend) or (transaction_type
                                              == TransactionType.Trade):
         h = h * 2
     return QSize(w, h)
Ejemplo n.º 7
0
    def draw(cls, x, y, self: PreparedText, painter: QPainter):
        font = QFont(self.fontName)
        if self.fontSize:
            font.setPointSizeF(self.fontSize)
        if self.fontBold:
            font.setBold(True)
        if self.fontItalic:
            font.setItalic(True)
        brushStyle = self.brushStyle or Qt.BrushStyle.SolidPattern
        w = self.width
        h = self.height
        tx = self.left + x
        ty = self.top + y
        if self.border:
            w -= self.border.width
            h -= self.border.width * 2
            tx += self.border.width
            ty += self.border.width
        rect = QRectF(tx, ty, w, h)

        if self.backColor:
            painter.setBrush(brush_style_map[brushStyle])
            painter.fillRect(rect, QColor('#' + hex(self.backColor)[2:]))
        if self.allowTags:
            doc = QTextDocument()
            doc.setDefaultFont(font)
            doc.setHtml(self.text)
            doc.setDocumentMargin(0)
            painter.save()
            painter.translate(tx + 2, ty + 1)
            doc.drawContents(painter, QRectF(0, 0, self.width, self.height))
            painter.restore()
        else:
            painter.save()
            painter.setFont(font)
            flags = cls.textFlags(self)
            rect.setX(rect.x() + 2)
            rect.setY(rect.y() + 1)
            painter.drawText(rect, flags, self.text)
            painter.restore()
        if self.border and self.border.color is not None:
            old_pen = painter.pen()
            pen = QPen(
                QColor(self.border.color), self.border.width,
                pen_style_map.get(self.border.style, Qt.PenStyle.SolidLine))
            painter.setPen(pen)
            painter.drawLines(
                cls.getLines(self, self.left + x, self.top + y,
                             self.left + self.width + x,
                             self.top + y + self.height))
            painter.setPen(old_pen)
Ejemplo n.º 8
0
 def f():
     doc = QTextDocument()
     tables = lookup(line.text())
     doc.setHtml(
         template.render(request={"script_root": ""},
                         tables=tables,
                         url_for=lambda *_, **__: None))
     doc.setTextWidth(doc.size().width())
     pixmap = QPixmap(doc.size().width(), doc.size().height())
     pixmap.fill(QColor(0, 0, 0, 0))
     painter = QPainter(pixmap)
     doc.drawContents(painter)
     painter.end()
     lab.setPixmap(pixmap)
     lab.setFixedSize(pixmap.size())
Ejemplo n.º 9
0
 def highlightCode(self, code, language):
     #converting the html to platin
     td = QTextDocument()
     td.setHtml(code)
     print("the plain text is here : " + td.toPlainText())
     codeLexer = get_lexer_by_name(language)
     f = open("highlightTest.html", 'wb')
     #fi = open("highlightTest.png",'wb')
     #style = get_style_by_name("native")
     formatter = HtmlFormatter(full=True, noclasses=True, encoding="UTF-8")
     #imgFormater = ImageFormatter()
     result = highlight(td.toPlainText(), codeLexer, formatter)
     td.setHtml(result.decode("UTF-8"))
     print(td.toHtml())
     return td.toHtml()
Ejemplo n.º 10
0
    def search_result(self):
        p = self.result_text_edit.palette()
        p.setColor(QPalette.Highlight, QColor("#ee799f"))
        self.result_text_edit.setPalette(p)

        search_settings = QTextDocument.FindFlags()

        mod = QApplication.keyboardModifiers()
        if (mod & Qt.ShiftModifier) != 0:
            search_settings |= QTextDocument.FindBackward

        r = self.result_text_edit.find(self.search_line.text(),
                                       search_settings)
        if not r:
            if (mod & Qt.ShiftModifier) != 0:
                self.goto(QTextCursor.End)
            else:
                self.goto(QTextCursor.Start)
            self.result_text_edit.find(self.search_line.text(),
                                       search_settings)

        if self.search_line.text() == '':
            self.search_summary_label.hide()
            return

        current_position = self.result_text_edit.textCursor().position()
        try:
            current_index = self.search_positions.index(current_position)
        except ValueError:
            current_index = -1

        self.search_summary_label.show()
        self.search_summary_label.setText(
            '%s/%s' % (current_index + 1, len(self.search_positions)))
Ejemplo n.º 11
0
Archivo: main.py Proyecto: safu9/Momiji
 def getFindFlags(self):
     flags = QTextDocument.FindFlags()
     if self.ui.buttonCase.isChecked():
         flags = flags | QTextDocument.FindCaseSensitively
     if self.ui.buttonWords.isChecked():
         flags = flags | QTextDocument.FindWholeWords
     return flags
    def sizeHint(self, option, index):

        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        doc = QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())
        return QSize(doc.idealWidth(), doc.size().height())
Ejemplo n.º 13
0
 def __openFile(self):
     fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
     if fname[0]:
         f = open(fname[0], 'r')
     with f:
         data = f.read()
         doc = QTextDocument(data, None)
         self.textEditLog.setDocument(doc)
Ejemplo n.º 14
0
 def __init(self):
     super.__init__()
     
     # Define attributes
     self.note = QTextDocument()
     self.deadline  = 0
     
     return
Ejemplo n.º 15
0
 def testWrite(self):
     text = 'foobar'
     doc = QTextDocument(text)
     b = QBuffer()
     b.open(QBuffer.ReadWrite)
     writer = QTextDocumentWriter(b, "plaintext")
     writer.write(doc)
     b.close()
     self.assertEqual(b.buffer(), text)
Ejemplo n.º 16
0
 def open_single_result_view(self, result_file):
     if isinstance(self.web_views[-1], QWebEngineView):
         self.web_views[-1].load(QUrl(result_file.as_uri()))
         self.web_views[-1].showMaximized()
     elif isinstance(self.web_views[-1], QTextBrowser):
         text_doc = QTextDocument()
         self.web_views[-1].setDocument(text_doc)
         self.web_views[-1].setSource(
             QUrl(result_file.as_uri(), QUrl.ParsingMode.TolerantMode))
         self.web_views[-1].show()
    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)
Ejemplo n.º 18
0
class DetailsDialog(QWidget):
    '''Dialog showing mod details'''
    def __init__(self, parent: QWidget, mod: Mod):
        super().__init__(parent)

        self.setWindowFlags(QtCore.Qt.Window)
        self.setObjectName("Details")
        self.resize(700, 800)
        self.setMinimumSize(600, 600)
        self.layout = QHBoxLayout(self)
        self.layout.setObjectName("layout")
        self.document = QTextDocument()
        self.document.setPlainText(str(mod))
        self.text = QTextEdit(self)
        self.text.setObjectName("text")
        self.text.setDocument(self.document)
        self.text.setAutoFormatting(QTextEdit.AutoAll)
        self.text.setReadOnly(True)
        self.text.setLineWrapMode(QTextEdit.NoWrap)
        self.layout.addWidget(self.text)

        self.setWindowTitle(mod.name + " " + TRANSLATE("Details", "Details"))
        QtCore.QMetaObject.connectSlotsByName(self)

    def adjustWidth(self):
        '''Fits size to content'''
        self.resize(
            self.document.idealWidth() + self.text.contentsMargins().left() +
            self.text.contentsMargins().right() +
            self.contentsMargins().left() + self.contentsMargins().right() +
            50, self.height())

    def showEvent(self, event):
        '''Qt show event'''
        super().showEvent(event)
        self.adjustWidth()

    def keyPressEvent(self, event):
        '''Qt KeyPressEvent override'''
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
Ejemplo n.º 19
0
    def __init__(self, parent: QWidget, mod: Mod):
        super().__init__(parent)

        self.setWindowFlags(QtCore.Qt.Window)
        self.setObjectName("Details")
        self.resize(700, 800)
        self.setMinimumSize(600, 600)
        self.layout = QHBoxLayout(self)
        self.layout.setObjectName("layout")
        self.document = QTextDocument()
        self.document.setPlainText(str(mod))
        self.text = QTextEdit(self)
        self.text.setObjectName("text")
        self.text.setDocument(self.document)
        self.text.setAutoFormatting(QTextEdit.AutoAll)
        self.text.setReadOnly(True)
        self.text.setLineWrapMode(QTextEdit.NoWrap)
        self.layout.addWidget(self.text)

        self.setWindowTitle(mod.name + " " + TRANSLATE("Details", "Details"))
        QtCore.QMetaObject.connectSlotsByName(self)
Ejemplo n.º 20
0
    def save_report(self, filename="", extension=".HTML"):
        """
        Save the generated report to the specified file
        Currently only html
        """
        full_filename = filename + extension.lower()
        full_filename = os.path.join(
            self._project_control.get_project_dir_absolute_path(),
            full_filename)

        if not self.report_html:
            self.__log.info("No report to save")
            return

        if extension == '.HTML':
            # HTML can contain non-ascii, so need to open with right encoding
            with open(full_filename, 'w', encoding='utf-8') as report_file:
                report_file.write(self.report_html)
                self.__log.info("Report written")
        elif extension == '.PDF':
            document = QTextDocument(parent=None)
            document.setHtml(self.report_html)
            printer = QPdfWriter(full_filename)
            printer.setPageSize(printer.A3)  # A3 to fit A4 page
            document.print_(printer)
        else:
            raise NotImplementedError

        # Show the generated report in the default browser
        url = os.path.realpath(full_filename)
        open_url(url=url)
Ejemplo n.º 21
0
    def saveOutputPDF(self):
        filesTypes = "Plik tekstowy (*.txt);;Plik PDF (*.pdf)"
        name, filter = QFileDialog.getSaveFileName(self.mainWindow,
                                                   'Zapisz plik', "Bez nazwy",
                                                   filesTypes)
        if not name:
            return
        if filter == "Plik PDF (*.pdf)":
            try:
                linesOriginalText = self.mainWindow.ui.plainTextEditOutputPDF.toPlainText(
                ).split("\n")
                template = pd.DataFrame(linesOriginalText,
                                        dtype=str,
                                        columns=[""])
                html = template.to_html(index=False, border=0)
                htmlFile = open("temp.html", "w", encoding="utf-8")
                htmlFile.write(html)
                htmlFile.close()

                doc = QTextDocument()
                try:
                    html = open("temp.html", "r", encoding="utf-8")
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z szablonem PDF \n" + str(inst))
                doc.setHtml(html.read())
                html.close()

                try:
                    printer = QPrinter()
                    printer.setOutputFileName(name)
                    printer.setOutputFormat(QPrinter.PdfFormat)
                    printer.setPageSize(QPrinter.A4)
                    printer.setPageMargins(4, 4, 4, 4, QPrinter.Millimeter)

                    doc.print_(printer)
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z generowaniem pliku PDF \n" +
                        str(inst))
                os.remove('temp.html')
            except Exception as inst:
                UiFunction.showErrorDialog(
                    "Wystąpił problem z tworzeniem pliku PDF \n" + str(inst))

        elif filter == "Plik tekstowy (*.txt)":
            try:
                try:
                    file = open(name, 'w')
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z wybranym plikiem \n" + str(inst))
                output = self.mainWindow.ui.plainTextEditOutputPDF.toPlainText(
                )
                file.write(output)
                file.close()
            except Exception as inst:
                UiFunction.showErrorDialog(
                    "Wystąpił problem z zapisem pliku \n" + str(inst))
Ejemplo n.º 22
0
    def add_task_item(self, iconIndex, title, note, deadline, expanded, indentLevel):
        """
        
        indentLevel: 0 = top-level item
        @return: None
        @author: 
        """
        
        # Add top level item
        newTaskItem = TaskItem(self)
        newTaskItem.setIcon(0, self.treeIconsList[iconIndex])
        newTaskItem.setText(0, title)
        newTaskItem.note = QTextDocument()
        newTaskItem.deadline = deadline        
        newTaskItem.setExpanded(expanded)

        return
Ejemplo n.º 23
0
    def insert_task_item(self, iconIndex, title, deadline, expanded, child):
        """
        Insert a new task item into the task tree with the supplied properties:
        
        iconIndex : index into treeIconsList specifying icon to be used for the node
        title: string of text used in tree
        deadline: int in ISO-8601 format of: YYYYMMDDHHMM
        expanded : True|False depending whether the node is to be expanded ot not
        child : True|False, depending on whether the task to be added is a child or not

        @return: None
        @author: pir
        """     
      
        if (self.topLevelItemCount() == 0):
            print("empty ItemTree instance")
            newTaskItem = TaskItem(self)
            self.setCurrentItem(newTaskItem, 0)
        else:
            print("container is not empty!")
            currentItem = self.currentItem()
            print(self.currentItem().text(0))   #test
            if (child == True):
                # Create child item
                newTaskItem = TaskItem(currentItem)
            else:
                # Create successor item
                print("creating successor item")    #test
                parentItem = currentItem.parent()
                print("type = ", type(parentItem))  #test 
                if (parentItem is None):
                    # Insert top level item
                    index = self.indexOfTopLevelItem(currentItem)
                    newTaskItem = TaskItem()
                    self.insertTopLevelItem(index + 1, newTaskItem)
                else:
                    newTaskItem = TaskItem(parentItem)

        # Add TaskItem to tree widget
        newTaskItem.setIcon(0, self.treeIconsList[iconIndex])
        newTaskItem.setText(0, title)
        newTaskItem.note = QTextDocument()
        newTaskItem.deadline = deadline        
        newTaskItem.setExpanded(expanded)
        
        return
Ejemplo n.º 24
0
    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                                                         # +++
    def paint(self, painter, option, index):
        """ Renders the delegate using the given painter and style option for the item specified by index. """

        # If the index is invalid we have nothing to draw
        if not index.isValid():
            return

        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        painter.save()

        # sometimes a paint event occurs after a element is removed selector static selection
        # but before qt list widget gets updated. This will cause isMissing and isFilteredOut to fail.
        # early out when this happens
        if options.text not in self._selector.staticSelection:
            return
        missing = self._selector.staticSelection.isMissing(options.text)
        filteredOut = self._selector.staticSelection.isFilteredOut(
            options.text)
        doc = QTextDocument()
        html = '''{0}'''.format(options.text)
        if filteredOut:
            html = '''<i>''' + html + '''</i>'''
        if missing:
            html = '''<s>''' + html + '''</s>'''
        doc.setHtml(html)

        options.text = ""

        #if options.widget is not None:
        QApplication.style().drawControl(QStyle.CE_ItemViewItem, options,
                                         painter)

        #Shift text right to make icon visible
        iconSize = options.icon.actualSize(
            options.rect.size()) if options.icon is not None else QSize(0, 0)
        painter.translate(options.rect.left() + iconSize.width(),
                          options.rect.top())
        clip = QRect(0, 0,
                     options.rect.width() + iconSize.width(),
                     options.rect.height())

        painter.setClipRect(clip)
        ctx = QAbstractTextDocumentLayout.PaintContext()
        #set text color to red for selected item
        if missing or filteredOut:
            ctx.palette.setColor(QPalette.Text, QColor(85, 85, 85))
        ctx.clip = clip
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Ejemplo n.º 26
0
Archivo: main.py Proyecto: nwagu/pablo
    def __init__(self, fileName=None):
        super(MainWindow, self).__init__()

        self.curFile = ''
        self.curPage = (
            0, 0
        )  # Tuple containing current page and total pages of the current file

        self.setWindowTitle('Pablo Editor')
        self.setWindowIcon(QIcon(
            GenUtils.resource_path('src/images/icon.ico')))
        self.setWindowState(Qt.WindowFullScreen)
        self.setWindowState(Qt.WindowMaximized)
        # available_geometry = app.desktop().availableGeometry(self)
        # self.resize(available_geometry.width(), available_geometry.height())
        self.readSettings()

        self.dropView = dropview.DropView()

        self.paged_text_edit = pagedtextedit.PagedTextEdit(self.dropView)
        # The textedit must be transparent; the white pages are painted in paintEvent() function
        self.paged_text_edit.setStyleSheet(
            "QTextEdit { background-color: transparent }")

        self.paged_text_edit.setFrameStyle(
            QFrame.NoFrame)  # Removes a border-like line around the TextEdit

        doc = QTextDocument()
        font = QFont()
        font.setPointSize(12)
        font.setFamily('Calibri')
        doc.setDefaultFont(font)
        # doc.setDefaultStyleSheet("body { font-color: black; font-family: Calibri; font-size: 12;} ")
        self.paged_text_edit.setDocument(doc)
        self.paged_text_edit.setPageFormat(QPageSize.A5Extra)
        self.paged_text_edit.setPageMargins(QMarginsF(15, 15, 15, 15))
        self.paged_text_edit.setUsePageMode(True)
        self.paged_text_edit.setPageNumbersAlignment(Qt.AlignBottom
                                                     | Qt.AlignCenter)

        self.text_edit_layout = QHBoxLayout()
        self.text_edit_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)

        self.text_edit_layout.setMargin(0)
        self.paged_text_edit.setLayout(self.text_edit_layout)

        # This below block of code prevents undoing the setDocumentMargin() and setFrameformat()
        # methods in the aboutUpdateDocumentGeometry function
        self.paged_text_edit.aboutUpdateDocumentGeometry()
        # self.paged_text_edit.document().clearUndoRedoStack() # this does not work
        # These commands work
        self.paged_text_edit.document().setUndoRedoEnabled(False)
        self.paged_text_edit.document().setUndoRedoEnabled(True)

        self.setCentralWidget(self.dropView)

        self.dropView.addWidget(self.paged_text_edit)
        self.dropView.setCurrentWidget(self.paged_text_edit)

        self._setup_components()

        self.setCurrentFile('')
        self.paged_text_edit.document().contentsChanged.connect(
            self.documentWasModified)
        self.paged_text_edit.currentCharFormatChanged.connect(
            self.updateFontWidgets)
        self.paged_text_edit.cursorPositionChanged.connect(
            self.updatePositions)
        self.paged_text_edit.pageInfo.connect(self.readPageInfo)

        self.statusBar.writeMessageOnStatus("Ready", 10000)
Ejemplo n.º 27
0
class QBlockCode(QCachedGraphicsItem):
    """
    Top-level code widget for a selection of text. Will construct an AST using
    QBlockCodeObj, mirroring the structure associated with the target object.
    This text is then rendered using a QTextDocument, with appropriate styles
    applied to it. Interaction events will be propagated to corresponding
    objects.
    """

    GRAPH_ADDR_SPACING = 20

    addr: int
    _addr_str: str
    obj: QBlockCodeObj
    _config: ConfigurationManager
    disasm_view: 'QDisassemblyBaseControl'
    workspace: 'Workspace'
    infodock: InfoDock
    parent: Any

    def __init__(self,
                 addr: int,
                 obj: QBlockCodeObj,
                 config: ConfigurationManager,
                 disasm_view: 'QDisassemblyBaseControl',
                 workspace: 'Workspace',
                 infodock: InfoDock,
                 parent: Any = None):
        super().__init__(parent=parent)
        self.addr = addr
        self._addr_str = "%08x" % self.addr
        self._addr_item: QGraphicsSimpleTextItem = None
        self.obj = obj
        self._width = 0
        self._height = 0
        self._config = config
        self.parent = parent
        self.workspace = workspace
        self.infodock = infodock
        self._disasm_view = disasm_view
        self._qtextdoc = QTextDocument()
        self._qtextdoc.setDefaultFont(self._config.disasm_font)
        self._qtextdoc.setDocumentMargin(0)

        self._addr_item = QGraphicsSimpleTextItem(self._addr_str, self)
        self._addr_item.setBrush(Conf.disasm_view_node_address_color)
        self._addr_item.setFont(Conf.disasm_font)

        self.update_document()
        self.setToolTip("Address: " + self._addr_str)

        self.refresh()

    def refresh(self):
        self._addr_item.setVisible(self._disasm_view.show_address)
        self._layout_items_and_update_size()

    def update_document(self):
        self._qtextdoc.clear()
        cur = QTextCursor(self._qtextdoc)
        self.obj.render_to_doc(cur)

    def paint(self, painter, option, widget):  #pylint: disable=unused-argument
        self.update_document()
        painter.setRenderHints(QPainter.Antialiasing
                               | QPainter.SmoothPixmapTransform
                               | QPainter.HighQualityAntialiasing)
        painter.setFont(self._config.disasm_font)

        if self.infodock.is_instruction_selected(
                self.addr) or self.obj.should_highlight_line:
            highlight_color = Conf.disasm_view_node_instruction_selected_background_color
            painter.setBrush(highlight_color)
            painter.setPen(highlight_color)
            painter.drawRect(0, 0, self.width, self.height)

        x = 0

        if self._disasm_view.show_address:
            x += self._addr_item.boundingRect().width(
            ) + self.GRAPH_ADDR_SPACING

        painter.translate(QPointF(x, 0))
        self._qtextdoc.drawContents(painter)

    #
    # Event handlers
    #

    def get_obj_for_mouse_event(self, event: QMouseEvent) -> QBlockCodeObj:
        p = event.pos()

        if self._disasm_view.show_address:
            offset = self._addr_item.boundingRect().width(
            ) + self.GRAPH_ADDR_SPACING
            p.setX(p.x() - offset)

        if p.x() >= 0:
            hitpos = self._qtextdoc.documentLayout().hitTest(
                p, Qt.HitTestAccuracy.ExactHit)
            if hitpos >= 0:
                return self.obj.get_hit_obj(hitpos)

        return None

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.infodock.select_instruction(self.addr)

        obj = self.get_obj_for_mouse_event(event)
        if obj is not None:
            obj.mousePressEvent(event)

    def mouseDoubleClickEvent(self, event):
        obj = self.get_obj_for_mouse_event(event)
        if obj is not None:
            obj.mouseDoubleClickEvent(event)

    #
    # Private methods
    #

    def _layout_items_and_update_size(self):
        self.update_document()

        x, y = 0, 0
        if self._disasm_view.show_address:
            self._addr_item.setPos(x, y)
            x += self._addr_item.boundingRect().width(
            ) + self.GRAPH_ADDR_SPACING

        x += self._qtextdoc.size().width()
        y += self._qtextdoc.size().height()
        self._width = x
        self._height = y
        self.recalculate_size()

    def _boundingRect(self):
        return QRectF(0, 0, self._width, self._height)
Ejemplo n.º 28
0
    painter.drawText(rect, Qt.AlignCenter, "QTEXAMPLE")
    painter.end()

    from PySide2.QtGui import QTextDocument
    from PySide2.QtPrintSupport import QPrinter
    from PySide2.QtWidgets import QTextEdit

    html = "<body><div align=center> Center </div>"
    html += "<div align=left> Left </div>"
    html += "<h1 align=center> Center title </h1>"
    html += "<p align=justify class=\"test1\"> {} </p>".format("Loren ipsum " *
                                                               1000)
    html += "<div align=right> End document </div></body>"

    document = QTextDocument()
    with open("style.css", "r") as fp:
        document.setDefaultStyleSheet(fp.read())
    document.setHtml(html)

    printer = QPrinter(QPrinter.PrinterResolution)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setPaperSize(QPrinter.A4)
    printer.setOutputFileName("file2.pdf")
    printer.setPageMargins(QMargins(10, 10, 10, 10))
    document.print_(printer)

    from PySide2.QtPrintSupport import QPrintPreviewWidget
    '''
    txtview = QTextEdit()
    txtview.setDocument(document)
Ejemplo n.º 29
0
 def __init__(self, text):
     QTextDocument.__init__(self, text)
    def testUndoRedo(self):
        text = 'foobar'
        doc = QTextDocument(text)

        self.assertFalse(doc.isRedoAvailable())
        self.assertTrue(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), text)

        cursor = QTextCursor(doc)
        doc.undo(cursor)

        self.assertTrue(doc.isRedoAvailable())
        self.assertFalse(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), '')

        doc.redo(cursor)

        self.assertFalse(doc.isRedoAvailable())
        self.assertTrue(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), text)
    def testUndoRedo(self):
        text = 'foobar'
        doc = QTextDocument(text)

        self.assertFalse(doc.isRedoAvailable())
        self.assertTrue(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), text)

        cursor = QTextCursor(doc)
        doc.undo(cursor)

        self.assertTrue(doc.isRedoAvailable())
        self.assertFalse(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), '')

        doc.redo(cursor)

        self.assertFalse(doc.isRedoAvailable())
        self.assertTrue(doc.isUndoAvailable())
        self.assertEqual(doc.toPlainText(), text)