def handlePaintRequest(self, printer): # find empty cells for row in range(self.tableView.rowCount()): for column in range(self.tableView.columnCount()): myitem = self.tableView.item(row, column) if myitem is None: item = QTableWidgetItem("") self.tableView.setItem(row, column, item) printer.setDocName(self.fname) document = QTextDocument() cursor = QTextCursor(document) model = self.tableView.model() tableFormat = QTextTableFormat() tableFormat.setBorder(0.2) tableFormat.setBorderStyle(3) tableFormat.setCellSpacing(0) tableFormat.setTopMargin(0) tableFormat.setCellPadding(4) table = cursor.insertTable(model.rowCount(), model.columnCount(), tableFormat) for row in range(table.rows()): for column in range(table.columns()): cursor.insertText(self.tableView.item(row, column).text()) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def printPreview(self, obj, data): from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog from PyQt5.QtGui import QTextDocument, QTextCursor, QTextTableFormat, QTextFrameFormat #, QFont import time self.printer = QPrinter() self.printer.setPageSize(QPrinter.A4) self.printer.setOrientation(QPrinter.Landscape) self.printer.setFullPage(True) self.printer.setPageMargins(2, 2, 2, 2, QPrinter.Millimeter) #self.printer.setFont(QFont("times",22)) dialog = QPrintPreviewDialog(self.printer) #dialog.showFullScreen() document = QTextDocument() #document.setHtml("<html><head></head><body></body></html>") document.setHtml("") cursor = QTextCursor(document) # Titolo cursor.insertHtml("<h2 align=center>%s</h2>" % obj['title']) cursor.insertText("\n") # Data cursor.insertHtml("<h5 align=left>%s</h5>" % time.strftime("%d/%m/%Y")) cursor.insertText("\n") # Table tableFormat = QTextTableFormat() tableFormat.setCellPadding(2) tableFormat.setCellSpacing(3) #tableFormat.setBorderStyle(QTextFrameFormat.BorderStyle_Ridge) tableFormat.setBorder(0) cursor.insertTable(len(data) + 2, len(obj['col_name']), tableFormat) # Intestazioni for table_title in obj['col_name']: cursor.insertHtml('<font size="4" color="blue"><b>%s</b></font>' % table_title) cursor.movePosition(QTextCursor.NextCell) # Riga bianca for table_title in obj['col_name']: cursor.insertText(' ') cursor.movePosition(QTextCursor.NextCell) # Dati Tabella for r in data: for k in obj['col_order']: v = r[k] if v is not None: #cursor.insertText(str(v)) cursor.insertHtml('<font size="4">%s</font>' % v) cursor.movePosition(QTextCursor.NextCell) dialog.paintRequested.connect(document.print_) dialog.setFixedSize(1500, 1050) dialog.exec_()
def insert(self): cursor = self.text.textCursor() # Get the configurations rows = self.rows.value() cols = self.cols.value() if not rows or not cols: popup = QtWidgets.QMessageBox( QtWidgets.QMessageBox.Warning, "Parameter error", "Row and column numbers may not be zero!", QtWidgets.QMessageBox.Ok, self) popup.show() else: padding = self.pad.value() space = self.space.value() # Set the padding and spacing fmt = QTextTableFormat() fmt.setCellPadding(padding) fmt.setCellSpacing(space) # Inser the new table cursor.insertTable(rows, cols, fmt) self.close()
def handlePaintRequest(self, printer): printer.setDocName(self.fname) document = QTextDocument() cursor = QTextCursor(document) model = self.tableView.model() tableFormat = QTextTableFormat() tableFormat.setBorder(0.2) tableFormat.setBorderStyle(3) tableFormat.setCellSpacing(0) tableFormat.setTopMargin(0) tableFormat.setCellPadding(4) table = cursor.insertTable(model.rowCount() + 1, model.columnCount(), tableFormat) model = self.tableView.model() ### get headers myheaders = [] for i in range(0, model.columnCount()): myheader = model.headerData(i, Qt.Horizontal) cursor.insertText(str(myheader)) cursor.movePosition(QTextCursor.NextCell) ### get cells for row in range(0, model.rowCount()): for col in range(0, model.columnCount()): index = model.index(row, col) cursor.insertText(str(index.data())) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def newLetter(self): self.textEdit.clear() cursor = self.textEdit.textCursor() cursor.movePosition(QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) textFormat = QTextCharFormat() boldFormat = QTextCharFormat() boldFormat.setFontWeight(QFont.Bold) italicFormat = QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(Qt.AlignRight) ##The Firm Box cursor.insertTable(1, 1, tableFormat) cursor.insertText("The Firm", boldFormat) cursor.insertBlock() cursor.insertText("321 City Street", textFormat) cursor.insertBlock() cursor.insertText("Industry Park") cursor.insertBlock() cursor.insertText("Some Country") cursor.setPosition(topFrame.lastPosition()) ##The Firm Box 아래 편지부분 cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Dear ", textFormat) cursor.insertText("NAME", italicFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Yours sincerely,", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("The Boss", textFormat) cursor.insertBlock() cursor.insertText("ADDRESS", italicFormat)
def table(self): self.tableRows = self.sb_rows.text() self.tableCols = self.sb_cols.text() self.tableSpacing = self.sb_spacing.text() self.tablePadding = self.sb_padding.text() tableFormatting = QTextTableFormat() tableFormatting.setCellPadding(int(self.tablePadding)) tableFormatting.setCellSpacing(int(self.tableSpacing)) cursor = self.currentEdit().textCursor() table = cursor.insertTable(int(self.tableRows), int(self.tableCols), tableFormatting)
def SaveTableImage(table): pixmap = table.grab() pixmap.save("widget.png") SaveTableImage(table) nrows = table.rowCount() ncols = table.columnCount() doc = QTextDocument() cursor = QTextCursor(doc) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(0) tableFormat.setCellSpacing(0) tableFormat.setBorder(1) tableFormat.setBorderBrush(QBrush(Qt.SolidPattern)) tableFormat.clearColumnWidthConstraints() textTable = cursor.insertTable(nrows + 1, ncols, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setBackground(QColor("#DADADA")) for i in range(ncols): cell = textTable.cellAt(0, i) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(table.horizontalHeaderItem(i).text()) for i in range(nrows): for j in range(ncols): item = table.item(i, j) t = "" if item is None else str(item.text()) # if item.text().iEmpty(): # table.setItem(i,j,QTableWidgetItem("0")) cell = textTable.cellAt(i + 1, j) cellCursor = cell.firstCursorPosition() cellCursor.insertText(t) cursor.movePosition(QTextCursor.End) printer = QPrinter(QPrinter.PrinterResolution) printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName("w8.pdf") doc.setDocumentMargin(0) doc.setTextWidth(5) doc.print(printer)
def handlePaintRequest(self, printer): document = QTextDocument() document.setPageSize(QSizeF(printer.pageRect().size())) cursor = QTextCursor(document) tableFormat = QTextTableFormat() TableText = QTextCharFormat() TableText.setLayoutDirection(Qt.RightToLeft) # tableFormat.setAlignment(Qt.AlignCenter) tableFormat.setBackground(QColor('#d3fbf5')) tableFormat.setCellPadding(3) tableFormat.setCellSpacing(4) tableFormat.setLayoutDirection(Qt.RightToLeft) tableFormat.setBorderStyle(QTextTableFormat.BorderStyle_Double) TitrFormat = QTextCharFormat() fontTitr = QFont() fontTitr.setBold(True) TitrFormat.setFont(fontTitr) SotonFormat = QTextCharFormat() TitrFormat.setLayoutDirection(Qt.RightToLeft) # SotonFormat.setBackground(QColor('#EEF9C9')) SotonFormat.setFont(fontTitr) cursor.insertText(self.TableTitr + "\n", TitrFormat) model = self.ui.tableView_result.model() table = cursor.insertTable(model.rowCount() + 1, model.columnCount(), tableFormat) headers = [ 'پلاک', 'بخش', 'تعداد جلد', 'تعداد صفحات', 'نوع', 'همکار تقاضاکننده', 'تحویل گیرنده', 'علت درخواست', 'توضیحات', 'تاریخ تحویل', 'ساعت تحویل', 'تاریخ بازگشت', 'ساعت بازگشت' ] self.tableResult.insertRows(10, 10) for header in reversed(headers): cursor.insertText(header, SotonFormat) cursor.movePosition(QTextCursor.NextCell) for row in range(table.rows()): for column in reversed(range(table.columns())): cursor.insertText( self.tableResult.data(self.tableResult.index(row, column)), TableText) cursor.movePosition(QTextCursor.NextCell) cursor.movePosition(QTextCursor.NextBlock) cursor.insertText('- سامانه بایگانی ثبت ماسال -', TitrFormat) # printer.setFullPage(True) document.print_(printer)
def newLetter(self): self.textEdit.clear() cursor = self.textEdit.textCursor() cursor.movePosition(QTextCursor.Start) topFrame = cursor.currentFrame() topFrameFormat = topFrame.frameFormat() topFrameFormat.setPadding(16) topFrame.setFrameFormat(topFrameFormat) textFormat = QTextCharFormat() boldFormat = QTextCharFormat() boldFormat.setFontWeight(QFont.Bold) italicFormat = QTextCharFormat() italicFormat.setFontItalic(True) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(16) tableFormat.setAlignment(Qt.AlignRight) cursor.insertTable(1, 1, tableFormat) cursor.insertText("The Firm", boldFormat) cursor.insertBlock() cursor.insertText("321 City Street", textFormat) cursor.insertBlock() cursor.insertText("Industry Park") cursor.insertBlock() cursor.insertText("Some Country") cursor.setPosition(topFrame.lastPosition()) cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) cursor.insertBlock() cursor.insertBlock() cursor.insertText("Dear ", textFormat) cursor.insertText("NAME", italicFormat) cursor.insertText(",", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("Yours sincerely,", textFormat) for i in range(3): cursor.insertBlock() cursor.insertText("The Boss", textFormat) cursor.insertBlock() cursor.insertText("ADDRESS", italicFormat)
def insert_table(self): self.param = mainDialog() table_format = QTextTableFormat() table_format.setWidth(QTextLength(QTextLength.PercentageLength,50)) table_format.setAlignment(Qt.AlignCenter) table_format.setCellPadding(5) table_format.setCellSpacing(0) ret = self.param.exec_() if ret == 1: if self.param.border_style == 'Dotted': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Dotted) elif self.param.border_style == 'Groove': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Groove) elif self.param.border_style == 'Dashed': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Dashed) elif self.param.border_style == 'DotDotDash': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_DotDotDash) elif self.param.border_style == 'DotDash': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_DotDash) elif self.param.border_style == 'Double': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Double) elif self.param.border_style == 'Inset': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Inset) elif self.param.border_style == 'None': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Inset) elif self.param.border_style == 'Outset': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Outset) elif self.param.border_style == 'Ridge': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Ridge) elif self.param.border_style == 'Solid': table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid) if self.param.layout_Direction == 'Left To Right': table_format.setLayoutDirection(Qt.LeftToRight) elif self.param.layout_Direction == 'Right To Left': table_format.setLayoutDirection(Qt.RightToLeft) cursor = self.ui.textEdit.textCursor() cursor.insertTable(self.param.number_of_rows,self.param.number_of_columns,table_format) self.param.close()
def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName, VManager): ''' Create PDF QgsTask ''' QCoreApplication.processEvents() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) font_normal = QFont("Helvetica", 10, QFont.Normal) font_bold = QFont("Helvetica", 12, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOrientation(QPrinter.Portrait) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) printer.setPaperSize(QPrinter.A4) printer.setOutputFileName(out) printer.setPageMargins(15, 15, 15, 15, QPrinter.Point) printer.setColorMode(QPrinter.Color) document = QTextDocument() document.setDefaultFont(font_normal) cursor = QTextCursor(document) cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.insertHtml(""" <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> </p> <p style='text-align: center;'> <strong>Video : </strong>%s<strong> </p> <p style='text-align: center;'> <strong>TimeStamp : </strong>%s</p><br><br> """ % (fileName, timestamp)) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignCenter) cursor.insertBlock(centerFormat) textTable = cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cell = textTable.cellAt(0, column) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(VManager.horizontalHeaderItem(column).text()) row = 0 for key in sorted(data.keys()): cell0 = textTable.cellAt(row + 1, 0) cell1 = textTable.cellAt(row + 1, 1) cell2 = textTable.cellAt(row + 1, 2) if (row + 1) % 2 == 0: cell0.setFormat(alternate_background) cell1.setFormat(alternate_background) cell2.setFormat(alternate_background) cellCursor0 = cell0.firstCursorPosition() cellCursor0.insertText(str(key)) cellCursor1 = cell1.firstCursorPosition() cellCursor1.insertText(str(data[key][0])) cellCursor2 = cell2.firstCursorPosition() cellCursor2.insertText(str(data[key][1])) row += 1 cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>Current Frame</strong></p><br> """) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignHCenter) cursor.insertBlock(centerFormat) cursor.insertImage(frame.scaledToWidth(500)) QCoreApplication.processEvents() document.print_(printer) QCoreApplication.processEvents()
def SaveAsPDF(self): """ Save Table as pdf """ fileName, _ = QFileDialog.getSaveFileName(self, "Save File", "", "PDF Files (*.pdf)") if fileName == "": return try: videoName = self.player.fileName timestamp = self.player.player.position() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) rows = self.VManager.rowCount() columns = self.VManager.columnCount() printer = QPrinter(QPrinter.HighResolution) innerRect = printer.pageRect() sizeF = QSizeF(innerRect.size().width(), innerRect.size().height()) header = QTextDocument() header.setPageSize(sizeF) cursor_header = QTextCursor(header) format1 = QTextCharFormat() format1.setFontPointSize(16) cursor_header.insertHtml( "<p style='text-align: left;'><strong>Video</strong>: %s <strong> TimeStamp</strong>: %s </p>" % (videoName, timestamp)) cursor_header.insertHtml("<br><br><br> ") cursor_header.select(QTextCursor.Document) fragment_header = cursor_header.selection() document = QTextDocument() cursor = QTextCursor(document) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(5) tableFormat.setCellSpacing(5) cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.insertFragment(fragment_header) textTable = cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setBackground(QColor("#DADADA")) for column in range(columns): cell = textTable.cellAt(0, column) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText( self.VManager.horizontalHeaderItem(column).data( Qt.DisplayRole)) for row in range(rows): for column in range(columns): item = self.VManager.item(row, column) if item is not None: cell = textTable.cellAt(row + 1, column) cellCursor = cell.firstCursorPosition() cellCursor.insertText( self.VManager.item(row, column).text()) cursor.movePosition(QTextCursor.End) printer.setOrientation(QPrinter.Portrait) printer.setPageMargins(30, 100, 10, 40, QPrinter.DevicePixel) printer.setFullPage(True) printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fileName) document.print_(printer) QApplication.restoreOverrideCursor() qgsu.showUserAndLogMessage( QCoreApplication.translate("QgsFmvMetadata", "Succesfully creating PDF")) except Exception as e: QApplication.restoreOverrideCursor() qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvMetadata", "Failed creating PDF"), level=QGis.Warning) return return
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setBackground(QColor("#e0e0e0")) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(4) constraints = [ QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), ] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) frame = cursor.currentFrame() frameFormat = frame.frameFormat() frameFormat.setBorder(1) frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay - 1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(QDate.longDayName(weekDay), boldFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows() - 1, weekDay - 1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle( "Calendar for %s %d" % (QDate.longMonthName(self.selectedDate.month()), self.selectedDate.year()) )
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() #self.editor.setStyleSheet("QTextTableFormat {border-color:white}") date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() self.setStyleSheet( "selection-color: yellow;" "selection-background-color: black;" "border-width: 1px;border-style: solid;border-color: white;") tableFormat.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) tableFormat.setBackground(QColor('#ffffff')) tableFormat.setCellPadding(1) tableFormat.setCellSpacing(0) constraints = [ QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7), QTextLength(QTextLength.PercentageLength, 7) ] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) # frame = cursor.currentFrame() # frameFormat = frame.frameFormat() # frameFormat.setBorder(2) # frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) dayFormat = QTextCharFormat(format) #self.editor.setStyleSheet("color:red;") dayFormat.setForeground(QColor('#f44336')) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) highlightedFormat.setFontUnderline(True) highlightedFormat.setUnderlineColor(QColor('#f44336')) # highlightedFormat.setColor(Qt.white) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay - 1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(day[weekDay - 1], dayFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows() - 1, weekDay - 1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle("Calendar for %s %d" % (QDate.longMonthName( self.selectedDate.month()), self.selectedDate.year()))
def test(self): # 选中文本字符 cursor = self.textEdit.textCursor() # 每次点击必须获取新的textCursor # 打印当前光标的位置 print(cursor.position()) cursor.setPosition(3, QTextCursor.KeepAnchor) self.textEdit.setTextCursor(cursor) self.textEdit.setFocus() print(cursor.selectedText()) # 打印选中的文本 return None qc = QColor(255, 0, 0) self.textEdit.setTextBackgroundColor(qc) self.textEdit.setFocus() cursor = self.textEdit.textCursor() # 移动光标 cursor.movePosition(QTextCursor.Left, n=1) # 移动完成之后,在编辑器上显示出来 self.textEdit.setTextCursor(cursor) # 获取光标的焦点(未设置可以移动,但无法显示光标) self.textEdit.setFocus() cursor.insertText('hello') # 选中文本 cursor.select(QTextCursor.WordUnderCursor) print(cursor.selectionStart(), cursor.selectionEnd()) print(cursor.selectedText()) # 插入一个表格(行,列) ttf = QTextTableFormat() ttf.setCellSpacing(10.0) ttf.setCellPadding(10.0) cursor.insertTable(2, 3, ttf) # 插入一个列表 tlf = QTextListFormat() tlf.setStyle(QTextListFormat.ListDisc) cursor.insertList(tlf) cursor.insertList(QTextListFormat.ListDisc) # 利用文本光标插入纯文本或者HTML cursor.insertText('<h1>123</h1>') cursor.insertHtml('<h1>123</h1>') cursor.insertImage('./start.jpg') # 暂时无法显示 # 设置字体 qfont = QFont() qfont.setFamily('微软雅黑') self.textEdit.setCurrentFont(qfont) # 从当前光标处开始为微软雅黑 # 设置文档标题 self.textEdit.setDocumentTitle('第一次') self.textEdit.setFontFamily('微软雅黑') # 在文本末尾追加内容(文本类型自动识别) self.textEdit.append('123') self.textEdit.append('<h1>123</h1>') # 在光标处插入文本(需要手点确定光标位置)(不会覆盖之前的) self.textEdit.insertPlainText('123') self.textEdit.insertHtml('<h1>123</h1>') # 插入纯文本 self.textEdit.setPlainText('<h1>123</h1>') # 插入HTML self.textEdit.setHtml('<h1>123</h1>') # 自动识别文本类型 self.textEdit.setText('<h1>123</h1>') self.textEdit.setText('123')
def insertCalendar(self): self.editor.clear() cursor = self.editor.textCursor() cursor.beginEditBlock() date = QDate(self.selectedDate.year(), self.selectedDate.month(), 1) tableFormat = QTextTableFormat() tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setBackground(QColor('#e0e0e0')) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(4) constraints = [QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14), QTextLength(QTextLength.PercentageLength, 14)] tableFormat.setColumnWidthConstraints(constraints) table = cursor.insertTable(1, 7, tableFormat) frame = cursor.currentFrame() frameFormat = frame.frameFormat() frameFormat.setBorder(1) frame.setFrameFormat(frameFormat) format = cursor.charFormat() format.setFontPointSize(self.fontSize) boldFormat = QTextCharFormat(format) boldFormat.setFontWeight(QFont.Bold) highlightedFormat = QTextCharFormat(boldFormat) highlightedFormat.setBackground(Qt.yellow) for weekDay in range(1, 8): cell = table.cellAt(0, weekDay-1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(QDate.longDayName(weekDay), boldFormat) table.insertRows(table.rows(), 1) while date.month() == self.selectedDate.month(): weekDay = date.dayOfWeek() cell = table.cellAt(table.rows()-1, weekDay-1) cellCursor = cell.firstCursorPosition() if date == QDate.currentDate(): cellCursor.insertText(str(date.day()), highlightedFormat) else: cellCursor.insertText(str(date.day()), format) date = date.addDays(1) if weekDay == 7 and date.month() == self.selectedDate.month(): table.insertRows(table.rows(), 1) cursor.endEditBlock() self.setWindowTitle("Calendar for %s %d" % (QDate.longMonthName(self.selectedDate.month()), self.selectedDate.year()))
def printViaQCursor(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return logo = QPixmap(":/logo.png") headFormat = QTextBlockFormat() headFormat.setAlignment(Qt.AlignLeft) headFormat.setTextIndent(self.printer.pageRect().width() - logo.width() - 216) bodyFormat = QTextBlockFormat() bodyFormat.setAlignment(Qt.AlignJustify) lastParaBodyFormat = QTextBlockFormat(bodyFormat) lastParaBodyFormat.setPageBreakPolicy( QTextFormat.PageBreak_AlwaysAfter) rightBodyFormat = QTextBlockFormat() rightBodyFormat.setAlignment(Qt.AlignRight) headCharFormat = QTextCharFormat() headCharFormat.setFont(QFont("Helvetica", 10)) bodyCharFormat = QTextCharFormat() bodyCharFormat.setFont(QFont("Times", 11)) redBodyCharFormat = QTextCharFormat(bodyCharFormat) redBodyCharFormat.setForeground(Qt.red) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(2) document = QTextDocument() cursor = QTextCursor(document) mainFrame = cursor.currentFrame() page = 1 for statement in self.statements: cursor.insertBlock(headFormat, headCharFormat) cursor.insertImage(":/logo.png") for text in ("Greasy Hands Ltd.", "New Lombard Street", "London", "WC13 4PX", QDate.currentDate().toString(DATE_FORMAT)): cursor.insertBlock(headFormat, headCharFormat) cursor.insertText(text) for line in statement.address.split(", "): cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText(line) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Dear {0},".format(statement.contact)) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) balance = statement.balance() cursor.insertText( "The balance of your account is $ {0:,.2f}.".format( float(balance))) if balance < 0: cursor.insertBlock(bodyFormat, redBodyCharFormat) cursor.insertText("Please remit the amount owing " "immediately.") else: cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We are delighted to have done " "business with you.") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Transactions:") table = cursor.insertTable(len(statement.transactions), 3, tableFormat) row = 0 for date, amount in statement.transactions: cellCursor = table.cellAt(row, 0).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText(date.toString(DATE_FORMAT), bodyCharFormat) cellCursor = table.cellAt(row, 1).firstCursorPosition() if amount > 0: cellCursor.insertText("Credit", bodyCharFormat) else: cellCursor.insertText("Debit", bodyCharFormat) cellCursor = table.cellAt(row, 2).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) format = bodyCharFormat if amount < 0: format = redBodyCharFormat cellCursor.insertText("$ {0:,.2f}".format(float(amount)), format) row += 1 cursor.setPosition(mainFrame.lastPosition()) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We hope to continue doing business " "with you,") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Yours sincerely") cursor.insertBlock(bodyFormat) if page == len(self.statements): cursor.insertBlock(bodyFormat, bodyCharFormat) else: cursor.insertBlock(lastParaBodyFormat, bodyCharFormat) cursor.insertText("K. Longrey, Manager") page += 1 document.print_(self.printer)
def interp(self): self.reset() curve = self.curveCombobox.currentText().strip() if self.view is None: return if curve not in self.view.pointObjs or len( self.view.pointObjs[curve]) < 2: return xs = [] ys = [] for item in self.view.pointObjs[curve]: xs.append(item.pos().x()) ys.append(item.pos().y()) xs, ys = self.view.pointToCoord(xs, ys) xmin = None xmax = None xstep = None if self.minXTextBox.text().strip(): xmin = str2num(self.minXTextBox.text().strip()) self.view.proj.fitx[0] = xmin if xmin is None: xmin = min(xs) if self.maxXTextBox.text().strip(): xmax = str2num(self.maxXTextBox.text().strip()) self.view.proj.fitx[1] = xmax if xmax is None: xmax = max(xs) if self.stepXTextBox.text().strip(): xstep = str2num(self.stepXTextBox.text().strip()) self.view.proj.fitx[2] = xstep if xstep is None: xstep = (xmax - xmin) / 15 xnew = np.arange(xmin, xmax + xstep / 2, xstep) degree = int(self.degreeComboBox.currentText()) self.view.proj.degree = degree self.view.proj.precision = self.presicion ynew = interp(xs, ys, xnew, degree) xpos, ypos = self.view.coordToPoint(xnew, ynew) for i in range(1, len(xpos)): line = QGraphicsLineItem(xpos[i - 1], ypos[i - 1], xpos[i], ypos[i]) line.setZValue(10) line.setPen(QPen(Qt.yellow, 2, Qt.SolidLine)) self.interpCurveObjs.append(line) self.view.scene.addItem(line) self.minXTextBox.setText(str(xmin)) self.maxXTextBox.setText(str(xmax)) self.stepXTextBox.setText(str(xstep)) text = "interpolation points:\n\n" self.outTextBox.setText(text) cursor = QTextCursor(self.outTextBox.textCursor()) cursor.movePosition(QTextCursor.End) # move the end of documents ttf = QTextTableFormat() # 创建表格对象格式 ttf.setCellPadding(2) # 单元格内文本和边框距离 ttf.setCellSpacing(0) # 单元格线宽 ttf.setAlignment(Qt.AlignLeft) # 表格对齐模式 ttf.setBorder(0.5) # ttf.setColumnWidthConstraints( # (QTextLength(QTextLength.PercentageLength, 50), QTextLength(QTextLength.PercentageLength, 50))) # 百分比定义列宽 ttf.setColumnWidthConstraints( (QTextLength(QTextLength.FixedLength, 75), QTextLength(QTextLength.FixedLength, 75))) # 像素定义列宽 table = cursor.insertTable(len(xnew) + 1, 2, ttf) table.cellAt(0, 0).firstCursorPosition().insertHtml("<b>x</b>") table.cellAt(0, 1).firstCursorPosition().insertHtml("<b>y</b>") for i in range(len(xnew)): table.cellAt(i + 1, 0).firstCursorPosition().insertText( str(round(xnew[i], self.presicion))) table.cellAt(i + 1, 1).firstCursorPosition().insertText( str(round(ynew[i], self.presicion))) self.view.sigModified.emit(True)