Beispiel #1
0
    def tesIterator(self):
        edit = QTextEdit()
        cursor = edit.textCursor()
        fmt = QTextCharFormat()
        frags = []
        for i in range(10):
            fmt.setFontPointSize(i+10)
            frags.append("block%d"%i)
            cursor.insertText(frags[i], fmt)

        doc = edit.document()
        block = doc.begin()

        index = 0
        for i in block:
            self.assertEqual(i.fragment().text(), frags[index])
            index += 1
Beispiel #2
0
    def tesIterator(self):
        edit = QTextEdit()
        cursor = edit.textCursor()
        fmt = QTextCharFormat()
        frags = []
        for i in range(10):
            fmt.setFontPointSize(i + 10)
            frags.append("block%d" % i)
            cursor.insertText(frags[i], fmt)

        doc = edit.document()
        block = doc.begin()

        index = 0
        for i in block:
            self.assertEqual(i.fragment().text(), frags[index])
            index += 1
class DontTouchReference(UsesQApplication):
    '''Check if the QTextTable returned by QTextCursor.insertTable() is not
    referenced by the QTextCursor that returns it.'''
    def setUp(self):
        super(DontTouchReference, self).setUp()
        self.editor = QTextEdit()
        self.cursor = self.editor.textCursor()
        self.table = self.cursor.insertTable(1, 1)

    def testQTextTable(self):
        # methods which return QTextTable should not increment its reference
        self.assertEqual(getrefcount(self.table), 2)
        f = self.cursor.currentFrame()
        del f
        self.assertEqual(getrefcount(self.table), 2)
        # destroying the cursor should not raise any "RuntimeError: internal
        # C++ object already deleted." when accessing the QTextTable
        del self.cursor
        self.assertEqual(getrefcount(self.table), 2)
        cell = self.table.cellAt(0, 0)
Beispiel #4
0
class DontTouchReference(UsesQApplication):
    """Check if the QTextTable returned by QTextCursor.insertTable() is not
    referenced by the QTextCursor that returns it."""

    def setUp(self):
        super(DontTouchReference, self).setUp()
        self.editor = QTextEdit()
        self.cursor = self.editor.textCursor()
        self.table = self.cursor.insertTable(1, 1)

    def testQTextTable(self):
        # methods which return QTextTable should not increment its reference
        self.assertEqual(getrefcount(self.table), 2)
        f = self.cursor.currentFrame()
        del f
        self.assertEqual(getrefcount(self.table), 2)
        # destroying the cursor should not raise any "RuntimeError: internal
        # C++ object already deleted." when accessing the QTextTable
        del self.cursor
        self.assertEqual(getrefcount(self.table), 2)
        cell = self.table.cellAt(0, 0)
Beispiel #5
0
class AppWindow(QMainWindow):

    # =====================
    # The Main Window Class
    # =====================

    def __init__(self):
        # ====================
        # Constructor Function
        # ====================

        QMainWindow.__init__(self)
        self.setWindowTitle("Virtua Text Editor")
        self.setGeometry(300, 300, 1024, 768)

        QToolTip.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.setToolTip('Application Window')

        # ================================
        # Function to setup menus, etc etc
        # ================================
        self.textEdit = QTextEdit()
        self.textEdit.setFont(QFont("Ubuntu", 12, QFont.Normal))
        self.setCentralWidget(self.textEdit)
        self.create_menus()
        self.create_actions()

        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveasAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu.addAction(self.undoAction)
        self.editMenu.addAction(self.redoAction)
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.selectallAction)
        self.editMenu.addAction(self.deselectallAction)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.findReplaceAction)

        self.helpMenu.addAction(self.aboutAction)

        self.app_status_bar = QStatusBar()
        self.app_status_bar.showMessage('Ready, v0.2', 10000)
        self.setStatusBar(self.app_status_bar)

        self.create_toolbar()
        self.toolbar.addAction(self.newAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.cutAction)
        self.toolbar.addAction(self.copyAction)
        self.toolbar.addAction(self.pasteAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.printAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.undoAction)
        self.toolbar.addAction(self.redoAction)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.findAction)
        self.toolbar.addAction(self.findReplaceAction)


    def create_toolbar(self):
        # ===============================
        # Function to create the toolbar.
        # ===============================
        self.toolbar = self.addToolBar('Main')
        self.toolbar.setToolButtonStyle(PySide.QtCore.Qt.ToolButtonTextUnderIcon)

    def newfile(self):
        self.textEdit.setText('')

    # TODO: Create the file/open method
    def openfile(self):
        print "Open File Menu Selected"

    # TODO: Create the file/save method
    def savefile(self):
        print "Save File Menu Selected"

    # TODO: Create the file/saveas method
    def saveasfile(self):
        print "Save As File Menu Selected"

    # TODO: Create the print method
    def print_page(self):
        print "Print Page Selected"

    # TODO: Create the find method
    def find_text(self):
        print "Find text option selected"

    # TODO: Create the replace method
    def find_replace_text(self):
        print "Replace text selected"

    def create_actions(self):
        # =========================================
        # Function to create actions for menu items
        # =========================================

        self.newAction = QAction(QIcon('digital_assets/document-new.svg'), 'New', self)
        self.newAction.setShortcut(QKeySequence.New)
        self.newAction.setStatusTip("Create a New File")
        self.newAction.setIconText("New")
        self.newAction.triggered.connect(self.newfile)

        self.openAction = QAction(QIcon('digital_assets/document-open.svg'), 'Open', self)
        self.openAction.setShortcut(QKeySequence.Open)
        self.openAction.setStatusTip("Open a file")
        self.openAction.triggered.connect(self.openfile)

        self.saveAction = QAction(QIcon('digital_assets/document-save.svg'), 'Save', self)
        self.saveAction.setShortcut(QKeySequence.Save)
        self.saveAction.setStatusTip("Save a file")
        self.saveAction.triggered.connect(self.savefile)

        self.saveasAction = QAction(QIcon('digital_assets/document-save-as.svg'), 'Save As', self)
        self.saveasAction.setShortcut(QKeySequence.SaveAs)
        self.saveasAction.setStatusTip("Save a File As....")
        self.saveasAction.triggered.connect(self.saveasfile)

        self.printAction = QAction(QIcon('digital_assets/document-print.svg'), 'Print', self)
        self.printAction.setShortcut(QKeySequence.Print)
        self.printAction.setStatusTip("Print")
        self.printAction.triggered.connect(self.print_page)

        self.exitAction = QAction(QIcon('digital_assets/application-exit.svg'), 'Exit', self)
        self.exitAction.setShortcut(QKeySequence.Quit)
        self.exitAction.setStatusTip("Exit the Application")
        self.exitAction.triggered.connect(self.quit_application)

        self.undoAction = QAction(QIcon('digital_assets/undo.svg'), 'Undo', self)
        self.undoAction.setShortcut(QKeySequence.Undo)
        self.undoAction.setStatusTip("Undo")
        self.undoAction.triggered.connect(self.textEdit.undo)

        self.redoAction = QAction(QIcon('digital_assets/redo.svg'), 'Redo', self)
        self.redoAction.setShortcut(QKeySequence.Redo)
        self.redoAction.setStatusTip("Redo")
        self.redoAction.triggered.connect(self.textEdit.redo)

        self.cutAction = QAction(QIcon('digital_assets/edit-cut.svg'), 'Cut', self)
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.cutAction.setStatusTip("Cut")
        self.cutAction.setEnabled(False)
        self.cutAction.triggered.connect(self.textEdit.cut)

        self.copyAction = QAction(QIcon('digital_assets/edit-copy.svg'), 'Copy', self)
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.copyAction.setStatusTip("Copy")
        self.copyAction.setEnabled(False)
        self.copyAction.triggered.connect(self.textEdit.copy)

        self.pasteAction = QAction(QIcon('digital_assets/edit-paste.svg'), 'Paste', self)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.pasteAction.setStatusTip("Paste")
        self.pasteAction.setEnabled(False)
        self.pasteAction.triggered.connect(self.textEdit.paste)

        self.selectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Select All', self)
        self.selectallAction.setShortcut(QKeySequence.SelectAll)
        self.selectallAction.setStatusTip("Select All")
        self.selectallAction.triggered.connect(self.textEdit.selectAll)

        self.deselectallAction = QAction(QIcon('digital_assets/edit-select-all.svg'), 'Deselect All', self)
        self.deselectallAction.setShortcut("Shift+Ctrl+A")
        self.deselectallAction.setStatusTip("Deselect All")
        self.deselectallAction.triggered.connect(self.deselect_all_text)

        self.findAction = QAction(QIcon('digital_assets/edit-find.svg'), 'Find', self)
        self.findAction.setShortcut(QKeySequence.Find)
        self.findAction.setStatusTip("Find")
        self.findAction.triggered.connect(self.find_text)

        self.findReplaceAction = QAction(QIcon('digital_assets/edit-find-replace.svg'), 'Replace', self)
        self.findReplaceAction.setShortcut(QKeySequence.Replace)
        self.findReplaceAction.setShortcut("Replace")
        self.findReplaceAction.triggered.connect(self.find_replace_text)

        self.aboutAction = QAction(QIcon('digital_assets/AppIcon.png'), 'About', self)
        self.aboutAction.setStatusTip("Displays info about the application")
        self.aboutAction.triggered.connect(self.show_about)


    def deselect_all_text(self):
        text_cursor = self.textEdit.textCursor()
        text_cursor.clearSelection()
        self.textEdit.setTextCursor(text_cursor)

    def create_menus(self):
        # ================================
        # Function to create the menu bar.
        # ================================
        self.fileMenu = self.menuBar().addMenu("File")
        self.fileMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.editMenu = self.menuBar().addMenu("Edit")
        self.editMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))
        self.helpMenu = self.menuBar().addMenu("Help")
        self.helpMenu.setFont(QFont("Ubuntu", 10, QFont.Normal))

    def set_icon(self):
        # ===============================
        # Function to set the Window Icon
        # ===============================
        appicon = QIcon('digital_assets/AppIcon.png')
        self.setWindowIcon(appicon)

    def quit_application(self):
        # ================================
        # Function to quit the application
        # ================================
        userinfo = QMessageBox.question(self, "Confirmation", "This will quit, Do you want to continue?",
                                        QMessageBox.Yes | QMessageBox.No)
        if userinfo == QMessageBox.Yes:
            templateApp.quit()
        if userinfo == QMessageBox.No:
            pass

    def show_about(self):
        QMessageBox.about(self, "About Virtua Text Editor",
                          "<b><h3>Virtua Text Editor</h3></b>"
                          "<p><h4>Virtua Text Editor has been written to serve as a template"
                          " that can be used as a basis for creating a working application."
                          " All of the components that make up the core functions of an"
                          " application, the main window, a status bar, menus and dialogs"
                          " are provided here as a basis for writing something new and interesting</h4></p>")

    def center_application(self):
        # ============================================
        # Function to center the Application on screen
        # ============================================
        qrect = self.frameGeometry()
        centerpoint = QDesktopWidget().availableGeometry().center()
        qrect.moveCenter(centerpoint)
        self.move(qrect.topLeft())
Beispiel #6
0
class MainWindow(QMainWindow):
    def __init__(self):

        # QMainWindow.__init__(self)
        super().__init__()      # use super() to avoid explicit dependency on the base class name
                                # Note: must not pass the self reference to __init__ in this case!
        self.resize(800, 600)

        # Create the main content widget
        mainWidget = QWidget(self)
        self.setCentralWidget(mainWidget)

        # Create a text component at the top area of the main widget
        self.output = QTextEdit(mainWidget)
        self.output.setReadOnly(True)
        self.output.setLineWrapMode(QTextEdit.NoWrap);

        # set the font
        font = self.output.font()
        font.setFamily("Courier")
        font.setPointSize(10)
        self.output.setFont(font)

        # Set the background color
        # self.output.setTextBackgroundColor(Qt.red) # Only sets the background color for the text itself, not for the whole widget
        pal = self.output.palette()
        pal.setColor(QPalette.Base, Qt.black)
        self.output.setPalette(pal)

        mainLayout = QVBoxLayout(mainWidget)
        mainLayout.addWidget(self.output)

        # Create buttons in a grid layout below the top area
        buttonWidget = QWidget(mainWidget)
        self.buttonLayout = QGridLayout(buttonWidget)
        mainLayout.addWidget(buttonWidget)

        # Add some buttons to execute python code
        self.row = 0
        self.column = 0
        self.addButton("Clear console", lambda : self.output.clear())
        self.newRow()

        # Add buttons for all the examples - attention: do not make "examples"
        # a local variable - otherwise, the Examples object would be destroyed
        # at the end of __init__ !!!
        self.examples = samplePackage.SampleModule.Examples(self)
        for example in self.examples.getExamples():
            if example is None:
                self.newRow()
            else:
                self.addButton(example.label, example.function)

        # In a Python program, sys.excepthook is called just before the program exits.
        # So we can catch all fatal, uncaught exceptions and log them.
        # NOTE: we must be sure not to set the excepthook BEFORE we an actually
        # log something!! 
        sys.excepthook = self.logException

        self.writelnColor(Qt.magenta, 
                          "Python version: {0}.{1}.{2} ({3})".format(
                              sys.version_info[0], 
                              sys.version_info[1], 
                              sys.version_info[2], 
                              sys.version_info[3]))
        self.writelnColor(Qt.magenta, 
                          "Qt version    : {0}".format(qVersion()))


    def logException(self, exctype, value, tb):
        self.writelnColor(Qt.red, 
                          ("\nFATAL ERROR: Uncaught exception\n"
                           "  {}: {}\n"
                           "{}\n".format(exctype.__name__, value, ''.join(traceback.format_tb(tb)))) )


    def addButton(self, label, function):
        theButton = QPushButton(label)
        theButton.clicked.connect(function)
        self.buttonLayout.addWidget(theButton, self.row, self.column)
        self.column += 1


    def newRow(self):
        self.row += 1
        self.column = 0


    def writeColor(self, color, *text):
        theText =  ' '.join(map(str, text))
        self.output.setTextColor(color)

        # Note: append() adds a new paragraph!
        #self.output.append(theText)
        self.output.textCursor().movePosition(QTextCursor.End)
        self.output.insertPlainText(theText)

        # scroll console window to bottom        
        sb = self.output.verticalScrollBar()
        sb.setValue(sb.maximum())


    def write(self, *text):
        self.writeColor(Qt.green, *text)


    def writelnColor(self, color, *text):
        self.writeColor(color, *text)
        self.write('\n')


    def writeln(self, *text):
        self.writelnColor(Qt.green, *text)
Beispiel #7
0
class qNotebook(QVBoxLayout):
    def __init__(self):
        QVBoxLayout.__init__(self)
        self._teditor = QTextEdit()
        self._teditor.setMinimumWidth(500)
        self._teditor.setStyleSheet("font: 12pt \"Courier\";")
        button_layout = QHBoxLayout()
        self.addLayout(button_layout)
        self.clear_but = qmy_button(button_layout, self.clear_all, "clear")
        self.copy_but = qmy_button(button_layout, self._teditor.copy, "copy")
        qmy_button(button_layout, self._teditor.selectAll, "select all")
        qmy_button(button_layout, self._teditor.undo, "undo")
        qmy_button(button_layout, self._teditor.redo, "redo")
        search_button = qButtonWithArgumentsClass("search", self.search_for_text, {"search_text": ""})
        button_layout.addWidget(search_button)
        qmy_button(button_layout, self.save_as_html, "save notebook")
        
        self.addWidget(self._teditor)
        self._teditor.document().setUndoRedoEnabled(True)
        self.image_counter = 0
        self.image_dict = {}
        self.image_data_dict = {}
        
    def append_text(self, text):
        self._teditor.append(str(text))
        
    def search_for_text(self, search_text = " "):
        self._teditor.find(search_text)
        
    def clear_all(self):
        self._teditor.clear()
        self.image_dict = {}
        self.image_counter = 0
#        newdoc = QTextDocument()
#        self._teditor.setDocument(newdoc)
        
    def append_image(self, fig=None):
        #This assumes that an image is there waiting to be saved from matplotlib
        self.imgdata = StringIO.StringIO()
        if fig is None:
            pyplot.savefig(self.imgdata, transparent = False, format = img_format)
        else:
            fig.savefig(self.imgdata, transparent = False, format = img_format)
        self.abuffer = QBuffer()
        self.abuffer.open(QBuffer.ReadWrite)
        self.abuffer.write(self.imgdata.getvalue())
        self.abuffer.close()
        
        self.abuffer.open(QBuffer.ReadOnly)
        iReader = QImageReader(self.abuffer, img_format )
        the_image = iReader.read()
        # the_image = the_image0.scaledToWidth(figure_width)
        
        # save the image in a file
        imageFileName = "image" + str(self.image_counter) + "." + img_format
        self.image_data_dict[imageFileName] = self.imgdata
        
        self.image_counter +=1
        imageFormat = QTextImageFormat()
        imageFormat.setName(imageFileName)
        imageFormat.setWidth(image_width)
        self.image_dict[imageFileName] = the_image
        
        #insert the image in the text document
        text_doc = self._teditor.document()
        text_doc.addResource(QTextDocument.ImageResource, QUrl(imageFileName), the_image)
        cursor = self._teditor.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertImage(imageFormat)
        
    def add_image_data_resource(self, imgdata, imageFileName):
        
        self.abuffer = QBuffer()
        self.abuffer.open(QBuffer.ReadWrite)
        self.abuffer.write(imgdata.getvalue())
        self.abuffer.close()
        
        self.abuffer.open(QBuffer.ReadOnly)
        iReader = QImageReader(self.abuffer, img_format )
        the_image = iReader.read()
        # the_image = the_image0.scaledToWidth(figure_width)
        
        # save the image in a file
        # imageFileName = "image" + str(self.image_counter) + "." + img_format
        self.image_data_dict[imageFileName] = imgdata
        
        # self.image_counter +=1
        imageFormat = QTextImageFormat()
        imageFormat.setName(imageFileName)
        imageFormat.setWidth(image_width)
        self.image_dict[imageFileName] = the_image
        
        #insert the image in the text document
        text_doc = self._teditor.document()
        text_doc.addResource(QTextDocument.ImageResource, QUrl(imageFileName), the_image)
        
    
    def append_html_table_from_array(self, a, header_rows=0, precision = 3, caption = None, cmap = None):
        nrows = len(a)
        ncols = len(a[0])
        result_string = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">\n"
        if caption != None:
            result_string += "<caption>%s</caption>\n"  % caption
        r = 0
        while r < header_rows:
            result_string += "<tr>"
            for c in range(ncols):
                if a[r][c] != "":
                    # count following blank columns
                    count = 1
                    while ((c+count) < len(a[r])) and (a[r][c+count] == "") :
                        count += 1
                    val = a[r][c]
                    if (type(val) == numpy.float64) or (type(val) == float):  # @UndefinedVariable
                        if precision != 999:
                            val = round(val, precision)
                    if count > 1:
                        result_string +="<th colspan=%s>%s</th>"  % (count, val)
                    else:
                        result_string += "<th>%s</th>"  % val
            result_string +="</tr>\n"
            r += 1
        while r < nrows:
            result_string += "<tr>"
            for c in range(ncols):
                val = a[r][c]
                if (cmap == None):
                    fcolor = "#ffffff"
                elif (type(val) == int) or (type(val) == float) or (type(val) == numpy.float64):  # @UndefinedVariable
                    fcolor = cmap.color_from_val(val)
                else:
                    fcolor = "#ffffff"
      
                if (val != "") or (c == 0):
                    if (type(val) == numpy.float64) or (type(val) == float): # @UndefinedVariable
                        if precision != 999:
                            val = round(val, precision)
                    count = 1
                    while ((c+count) < len(a[r])) and (a[r][c+count] == "") :
                        count += 1
                    if count > 1:
                        result_string +="<td colspan=%s bgcolor=%s>%s</td>"  % (count, fcolor, val)
                    else:
                        result_string += "<td bgcolor=%s>%s</td>" % (fcolor, val)
            result_string +="</tr>\n"
            r += 1
        result_string += "</table>\n"
        self.append_text(result_string)
        
    def create_empty_string_array(self, rows, cols):
        table_array = []
        for r in range(rows): #@UnusedVariable
            the_row = []
            for c in range(cols): #@UnusedVariable
                the_row.append("")
            table_array.append(the_row)
        return table_array
    
    def recurse_on_dict_headers(self, sdict, r, c, sorted_headers = None):
        if ((type(sdict) != dict) and (type(sdict) != OrderedDict)):
            return c + 1
        else:
            if sorted_headers != None:
                sheaders = sorted_headers
            else:
                sheaders = sorted(sdict.keys())
            for k in sheaders:
                self.table_array[r][c] = k
                c = self.recurse_on_dict_headers(sdict[k], r + 1, c)
            return c
        
    def recurse_to_find_size(self, sdict, r, c):
        
        if ((type(sdict) != dict) and (type(sdict) != OrderedDict)):
            return r, c + 1
        else:
            rbiggest = r
            for k in sorted(sdict.keys()):
                rnew, c = self.recurse_to_find_size(sdict[k], r + 1, c)
                if rnew > rbiggest:
                    rbiggest = rnew
            return rbiggest, c
                
    def recurse_on_dict(self, sdict, r, c, sorted_headers = None):
        if ((type(sdict) != dict) and (type(sdict) != OrderedDict)):
            self.table_array[r][c] = sdict
            return c + 1
        else:
            if sorted_headers != None:
                sheaders = sorted_headers
            else:
                sheaders = sorted(sdict.keys())
            for k in sheaders:
                c = self.recurse_on_dict(sdict[k], r, c)
            return c

    def convert_structured_dicts_to_array(self, sdict, sorted_keys = None, sorted_headers = None):
        header_levels, ncols = self.recurse_to_find_size(sdict[sdict.keys()[0]], 0, 0)
        nrows = header_levels + len(sdict.keys())
        self.table_array = self.create_empty_string_array(nrows, ncols)
        self.recurse_on_dict_headers(sdict[sdict.keys()[0]], 0, 0, sorted_headers)
        if sorted_keys != None:
            key_list = sorted_keys
        else:
            key_list = sdict.keys()
        r = header_levels
        for entry in key_list:
            c = 0
            self.table_array[r][0] = entry
            self.recurse_on_dict(sdict[entry], r, c, sorted_headers = sorted_headers)
            r += 1
        return self.table_array
            
    def append_html_table_from_dicts(self, sdict, header_rows = 1, title = None, sorted_keys = None, precision = 3, cmap = None, sorted_headers = None):
        the_array = self.convert_structured_dicts_to_array(sdict, sorted_keys, sorted_headers = sorted_headers)
        self.append_html_table_from_array(the_array, header_rows, caption = title, precision = precision, cmap = cmap)
    
    def append_table(self, rows, cols, border_style = QTextFrameFormat.BorderStyle_Solid):
        tformat = QTextTableFormat()
        tformat.setBorderStyle(border_style)
        cursor= self._teditor.textCursor()
        cursor.movePosition(QTextCursor.End)
        table = cursor.insertTable(rows, cols, tformat)
        return table
    
    def fill_table_cell(self, row, col, table, text):
        cptr = table.cellAt(row, col).firstCursorPosition()
        cptr.insertText(text)
        
    def save_as_html(self):
        fname = QFileDialog.getSaveFileName()[0]
        fdirectoryname = os.path.dirname(fname)
        # fdirectoryname = QFileDialog.getExistingDirectory()
        # print fdirectoryname
        # fname = fdirectoryname + "/report.html"
        text_doc = self._teditor.document()
        f = open(fname, 'w')
        f.write(text_doc.toHtml())
        f.close()
        for imageFileName in self.image_dict.keys():
            full_image_path = fdirectoryname + "/" + imageFileName
            iWriter = QImageWriter(full_image_path, img_format)
            iWriter.write(self.image_dict[imageFileName])
Beispiel #8
0
    def testCase(self):
        editor = QTextEdit()
        cursor = QTextCursor(editor.textCursor())
        cursor.movePosition(QTextCursor.Start)

        mainFrame = cursor.currentFrame()

        plainCharFormat = QTextCharFormat()
        boldCharFormat = QTextCharFormat()
        boldCharFormat.setFontWeight(QFont.Bold)
        cursor.insertText(
            """
                          Text documents are represented by the 
                          QTextDocument class, rather than by QString objects. 
                          Each QTextDocument object contains information about 
                          the document's internal representation, its structure, 
                          and keeps track of modifications to provide undo/redo 
                          facilities. This approach allows features such as the 
                          layout management to be delegated to specialized 
                          classes, but also provides a focus for the framework.""",
            plainCharFormat)

        frameFormat = QTextFrameFormat()
        frameFormat.setMargin(32)
        frameFormat.setPadding(8)
        frameFormat.setBorder(4)
        cursor.insertFrame(frameFormat)

        cursor.insertText(
            """
                          Documents are either converted from external sources 
                          or created from scratch using Qt. The creation process 
                          can done by an editor widget, such as QTextEdit, or by 
                          explicit calls to the Scribe API.""", boldCharFormat)

        cursor = mainFrame.lastCursorPosition()
        cursor.insertText(
            """
                          There are two complementary ways to visualize the 
                          contents of a document: as a linear buffer that is 
                          used by editors to modify the contents, and as an 
                          object hierarchy containing structural information 
                          that is useful to layout engines. In the hierarchical 
                          model, the objects generally correspond to visual 
                          elements such as frames, tables, and lists. At a lower 
                          level, these elements describe properties such as the 
                          style of text used and its alignment. The linear 
                          representation of the document is used for editing and 
                          manipulation of the document's contents.""",
            plainCharFormat)

        frame = cursor.currentFrame()

        items = []

        #test iterator
        for i in frame:
            items.append(i)

        #test __iadd__
        b = frame.begin()
        i = 0
        while not b.atEnd():
            self.assertEqual(b, items[i])
            self.assert_(b.parentFrame(), items[i].parentFrame())
            b.__iadd__(1)
            i += 1

        #test __isub__
        b = frame.end()
        i = 0
        while i > 0:
            self.assertEqual(b, items[i])
            self.assert_(b.parentFrame(), items[i].parentFrame())
            b.__isub__(1)
            i -= 1
Beispiel #9
0
    def testCase(self):
        editor = QTextEdit()
        cursor = QTextCursor(editor.textCursor())
        cursor.movePosition(QTextCursor.Start)
   
        mainFrame = cursor.currentFrame()
        
        plainCharFormat = QTextCharFormat()
        boldCharFormat = QTextCharFormat()
        boldCharFormat.setFontWeight(QFont.Bold);
        cursor.insertText("""
                          Text documents are represented by the 
                          QTextDocument class, rather than by QString objects. 
                          Each QTextDocument object contains information about 
                          the document's internal representation, its structure, 
                          and keeps track of modifications to provide undo/redo 
                          facilities. This approach allows features such as the 
                          layout management to be delegated to specialized 
                          classes, but also provides a focus for the framework.""",
                          plainCharFormat)

        frameFormat = QTextFrameFormat()
        frameFormat.setMargin(32)
        frameFormat.setPadding(8)
        frameFormat.setBorder(4)
        cursor.insertFrame(frameFormat)

        cursor.insertText("""
                          Documents are either converted from external sources 
                          or created from scratch using Qt. The creation process 
                          can done by an editor widget, such as QTextEdit, or by 
                          explicit calls to the Scribe API.""",
                          boldCharFormat)

        cursor = mainFrame.lastCursorPosition()
        cursor.insertText("""
                          There are two complementary ways to visualize the 
                          contents of a document: as a linear buffer that is 
                          used by editors to modify the contents, and as an 
                          object hierarchy containing structural information 
                          that is useful to layout engines. In the hierarchical 
                          model, the objects generally correspond to visual 
                          elements such as frames, tables, and lists. At a lower 
                          level, these elements describe properties such as the 
                          style of text used and its alignment. The linear 
                          representation of the document is used for editing and 
                          manipulation of the document's contents.""",
                          plainCharFormat)

        
        frame = cursor.currentFrame()

        items = []

        #test iterator
        for i in frame:
            items.append(i)

        #test __iadd__
        b = frame.begin()
        i = 0
        while not b.atEnd():
            self.assertEqual(b, items[i])
            self.assert_(b.parentFrame(), items[i].parentFrame())
            b.__iadd__(1)
            i += 1

        #test __isub__
        b = frame.end()
        i = 0
        while i > 0:
            self.assertEqual(b, items[i])
            self.assert_(b.parentFrame(), items[i].parentFrame())
            b.__isub__(1)
            i -= 1