async def openFileFromCheckout(self, relpath): if not await self.checkChanges(): return self.previewButton.setChecked(False) fp = Path(os.path.join(self.checkoutPath, relpath)) if not fp.exists(): return fsize = fp.stat().st_size if fsize > 0 and not await self.isTextFile(str(fp)): return messageBox('Not a text file') self.busy() basename = relpath doc = self.newDocument(name=basename) cursor = QTextCursor(doc) async for chunk in asyncReadTextFileChunked( str(fp), mode='rt'): await asyncio.sleep(0.1) cursor.insertText(chunk) self.currentDocument = doc self.busy(False) return doc
def fixUpLine(self, line: int, newText: str, data: int): """ The receiver of the 'fixupText' signal should invoke this method to replace the line with the cleaned text and the model's matching row """ block = self.document().findBlockByLineNumber(line) if block.isValid(): if block.userData() is None: block.setUserData(self._UserData(data)) else: block.userData().row = data text = newText.strip() if not text: block.setUserState(self._State.Blank) elif data < 0: block.setUserState(self._State.Error) else: block.setUserState(self._State.Fixup) cursor = QTextCursor(block) cursor.beginEditBlock() cursor.movePosition(QTextCursor.StartOfLine) cursor.select(QTextCursor.LineUnderCursor) cursor.removeSelectedText() cursor.insertText(text) cursor.endEditBlock()
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 setLine(self, line): cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.End) cursor.setPosition(self.newPromptPos, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor.insertText(line) self.setTextCursor(cursor)
def load(self, url=None, encoding=None, keepUndo=False): """Load the specified or current url (if None was specified). Currently only local files are supported. An IOError is raised when trying to load a nonlocal URL. If loading succeeds and an url was specified, the url is made the current url (by calling setUrl() internally). If keepUndo is True, the loading can be undone (with Ctrl-Z). """ if url is None: url = QUrl() u = url if not url.isEmpty() else self.url() text = self.load_data(u, encoding or self._encoding) if keepUndo: c = QTextCursor(self) c.select(QTextCursor.Document) c.insertText(text) else: self.setPlainText(text) self.setModified(False) if not url.isEmpty(): self.setUrl(url)
def titleSetext(self, level): cursor = self.textCursor() cursor.beginEditBlock() # Is it already a Setext header? if cursor.block().userState() in [ MS.MarkdownStateSetextHeading1Line2, MS.MarkdownStateSetextHeading2Line2 ]: cursor.movePosition(QTextCursor.PreviousBlock) text = cursor.block().text() if cursor.block().userState() in [ MS.MarkdownStateSetextHeading1Line1, MS.MarkdownStateSetextHeading2Line1 ]: # Need to remove line below c = QTextCursor(cursor.block().next()) self.selectBlock(c) c.insertText("") char = "=" if level == 1 else "-" text = re.sub(r"^#*\s*(.*)\s*#*", "\\1", text) # Removes # sub = char * len(text) text = text + "\n" + sub self.selectBlock(cursor) cursor.insertText(text) cursor.endEditBlock()
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 append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
def actionTriggered(self, name): # convert arpeggio_normal to arpeggioNormal, etc. name = _arpeggioTypes[name] cursor = self.mainwindow().textCursor() # which arpeggio type is last used? lastused = '\\arpeggioNormal' types = set(_arpeggioTypes.values()) block = cursor.block() while block.isValid(): s = types.intersection(tokeniter.tokens(block)) if s: lastused = s.pop() break block = block.previous() # where to insert c = lydocument.cursor(cursor) c.select_end_of_block() with cursortools.compress_undo(cursor): for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE): c = QTextCursor(cursor.document()) c.setPosition(item.end) c.insertText('\\arpeggio') if name != lastused: cursortools.strip_indent(c) indent = c.block().text()[:c.position() - c.block().position()] c.insertText(name + '\n' + indent) # just pick the first place return
def cmdJoinLines(self, cmd, repeatLineCount=None): if repeatLineCount is not None: self._selectRangeForRepeat(repeatLineCount) start, end = self._selectedLinesRange() count = end - start if not count: # nothing to join return self._saveLastEditLinesCmd(cmd, end - start + 1) cursor = QTextCursor(self._qpart.document().findBlockByNumber(start)) with self._qpart: for _ in range(count): cursor.movePosition(QTextCursor.EndOfBlock) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) self.moveToFirstNonSpace(cursor, QTextCursor.KeepAnchor) nonEmptyBlock = cursor.block().length() > 1 cursor.removeSelectedText() if nonEmptyBlock: cursor.insertText(' ') self._qpart.setTextCursor(cursor)
def actionTriggered(self, name): # convert arpeggio_normal to arpeggioNormal, etc. name = _arpeggioTypes[name] cursor = self.mainwindow().textCursor() # which arpeggio type is last used? lastused = '\\arpeggioNormal' types = set(_arpeggioTypes.values()) block = cursor.block() while block.isValid(): s = types.intersection(tokeniter.tokens(block)) if s: lastused = s.pop() break block = block.previous() # where to insert c = lydocument.cursor(cursor) c.select_end_of_block() with cursortools.compress_undo(cursor): for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE): c = QTextCursor(cursor.document()) c.setPosition(item.end) c.insertText('\\arpeggio') if name != lastused: cursortools.strip_indent(c) indent = c.block().text()[:c.position()-c.block().position()] c.insertText(name + '\n' + indent) # just pick the first place return
def insert_snippet(text, cursor, variables): """Inserts a normal text snippet. After the insert, the cursor points to the end of the inserted snippet. If this function returns a cursor it must be set as the cursor for the view after the snippet has been inserted. """ exp_base = expand.Expander(cursor) evs = [] # make a list of events, either text or a constant for text, key in snippets.expand(text): if text: evs.append(text) if key == '$': evs.append('$') elif key: # basic variables func = getattr(exp_base, key, None) if func: evs.append(func()) selectionUsed = expand.SELECTION in evs # do the padding if 'selection: strip;' is used if selectionUsed and 'strip' in variables.get('selection', ''): space = '\n' if '\n' in cursor.selection().toPlainText() else ' ' # change whitespace in previous and next piece of text i = evs.index(expand.SELECTION) for j in range(i-1, -i, -1): if evs[j] not in expand.constants: evs[j] = evs[j].rstrip() + space break for j in range(i+1, len(evs)): if evs[j] not in expand.constants: evs[j] = space + evs[j].lstrip() break # now insert the text ins = QTextCursor(cursor) selectionUsed and ins.setPosition(cursor.selectionStart()) a, c = -1, -1 for e in evs: if e == expand.ANCHOR: a = ins.position() elif e == expand.CURSOR: c = ins.position() elif e == expand.SELECTION: ins.setPosition(cursor.selectionEnd()) else: ins.insertText(e) cursor.setPosition(ins.position()) # return a new cursor if requested if (a, c) != (-1, -1): new = QTextCursor(cursor) if a != -1: new.setPosition(a) if c != -1: new.setPosition(c, QTextCursor.KeepAnchor if a != -1 else QTextCursor.MoveAnchor) return new
def cut_assign(cursor): """Cuts selected text and assigns it to a LilyPond variable.""" # ask the variable name name = inputdialog.getText(None, _("Cut and Assign"), _( "Please enter the name for the variable to assign the selected " "text to:"), regexp="[A-Za-z]+") if not name: return cursortools.strip_selection(cursor) # determine state at cursor block = cursortools.block(cursor) state = tokeniter.state(block) for t in tokeniter.partition(cursor).left: state.follow(t) mode = "" for p in state.parsers(): if isinstance(p, ly.lex.lilypond.ParseInputMode): if isinstance(p, ly.lex.lilypond.ParseLyricMode): mode = " \\lyricmode" elif isinstance(p, ly.lex.lilypond.ParseChordMode): mode = " \\chordmode" elif isinstance(p, ly.lex.lilypond.ParseFigureMode): mode = " \\figuremode" elif isinstance(p, ly.lex.lilypond.ParseDrumMode): mode = " \\drummode" break # find insertion place: found = False while block.previous().isValid(): block = block.previous() state = tokeniter.state(block) if isinstance(state.parser(), ly.lex.lilypond.ParseGlobal): found = True break tokens = tokeniter.tokens(block) for t in tokens: if isinstance(t, ly.lex.lilypond.Name): found = True break elif not isinstance(t, (ly.lex.Space, ly.lex.Comment)): break if found: break insert = QTextCursor(block) text = cursor.selection().toPlainText() space = '\n' if '\n' in text else ' ' text = ''.join((name, ' =', mode, ' {', space, text, space, '}\n\n')) with cursortools.compress_undo(cursor): cursor.insertText('\\' + name) pos = insert.selectionStart() insert.insertText(text) if metainfo.info(cursor.document()).auto_indent: insert.setPosition(pos, QTextCursor.KeepAnchor) with cursortools.compress_undo(insert, True): indent.re_indent(insert)
class Ui_MainWindow(object): def __init__(self): self.connection = connection self.cursor = cursor def loadData(self): self.cursor.execute("SELECT * FROM student") for i in range(cursor.rowcount): result = cursor.fetchone() print(i) for row in result: self.cursor = QTextCursor(self.textEdit.document()) self.cursor.insertText(row) def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.textEdit = QtWidgets.QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(30, 60, 481, 401)) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.textEdit.setFont(font) self.textEdit.setObjectName("textEdit") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(30, 20, 441, 21)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName("label") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(560, 60, 93, 28)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.loadData) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "Select Data from MySQL Database in PyQt5")) self.pushButton.setText(_translate("MainWindow", "Load Data"))
def make_text(text, size): document = QTextDocument() fmt = QTextCharFormat() font: QFont = QApplication.instance().font() font.setPixelSize(size) fmt.setFont(font) cursor = QTextCursor(document) cursor.insertText(text, fmt) return document
def _update_text(self, changes): """Apply the changes to our QTextDocument.""" c = QTextCursor(self.document()) c.beginEditBlock() for start, end, text in reversed(changes): c.setPosition(end) if start != end: c.setPosition(start, QTextCursor.KeepAnchor) c.insertText(text) c.endEditBlock()
def commentBlock(self, block): cursor = QTextCursor(block) text = block.text() if text[:5] == "<!-- " and \ text[-4:] == " -->": text2 = text[5:-4] else: text2 = "<!-- " + text + " -->" self.selectBlock(cursor) cursor.insertText(text2)
def search_and_replace(self, word, newWord = None, replace = False): self.textEdit.textCursor().beginEditBlock() doc = self.textEdit.document() cursor = QTextCursor(doc) while True: cursor = doc.find(word, cursor) if cursor.isNull(): break if replace and newWord is not None: cursor.insertText(newWord) self.textEdit.textCursor().endEditBlock()
def write(self, s): if self.echo: sys.__stdout__.write(s) doc = self.document() cursor = QTextCursor(doc) cursor.clearSelection() cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(s) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.clearSelection() self.ensureCursorVisible() qApp.processEvents()
def test_file_save(self): text = "Lorem Ipsum dolor sit amet." cursor = QTextCursor(self.window.current_editor.document()) cursor.insertText(text) self.window._save_to_path('/home/amey/test_new') file = open('/home/amey/test_new', 'r') file_text = file.read() file.close() self.assertEqual(self.window.current_editor.toPlainText(), file_text)
def _insertDoc(self, code: str): # def _insertDoc(self): # self.codeReview.insertPlainText("model = Sequential()"+'\n') # code = "test" doc = self.codeReview.document() curosr = QTextCursor(doc) searchText = "model = Sequential()" tmp = doc.find(searchText, curosr) if tmp is not None: curosr.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor, 0) curosr.insertText(code + '\n\n')
def actionTriggered(self, name): cursor = self.mainwindow().textCursor() style = _glissandoStyles[name] c = lydocument.cursor(cursor) c.select_end_of_block() for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE): c = QTextCursor(cursor.document()) c.setPosition(item.end) if style: text = "-\\tweak #'style #'{0} \\glissando".format(style) else: text = '\\glissando' c.insertText(text) return
def test_file_save_as(self): text = "Lorem Ipsum dolor sit amet." cursor = QTextCursor(self.window.current_editor.document()) cursor.insertText(text) new_path, _ = QFileDialog.getSaveFileName(self.window, 'Save File As') if new_path: self.window._save_to_path(new_path) file = open(new_path, 'r') file_text = file.read() file.close() self.assertEqual(self.window.current_editor.toPlainText(), file_text) else: self.assertTrue(True, "File path not selected")
def apply_changes(self): """Apply the changes and update the tokens.""" c = QTextCursor(self._d) # record a sensible position for undo c.setPosition(self._changes_list[-1][0]) c.joinPreviousEditBlock() if self.combine_undo else c.beginEditBlock() try: for start, end, text in self._changes_list: c.movePosition(QTextCursor.End) if end is None else c.setPosition(end) c.setPosition(start, QTextCursor.KeepAnchor) c.insertText(text) finally: c.endEditBlock() if self.combine_undo is None: self.combine_undo = True
def apply_changes(self): """Apply the changes and update the tokens.""" c = QTextCursor(self._d) # record a sensible position for undo c.setPosition(self._changes_list[-1][0]) c.joinPreviousEditBlock() if self.combine_undo else c.beginEditBlock() try: for start, end, text in self._changes_list: c.movePosition( QTextCursor.End) if end is None else c.setPosition(end) c.setPosition(start, QTextCursor.KeepAnchor) c.insertText(text) finally: c.endEditBlock() if self.combine_undo is None: self.combine_undo = True
def html_copy(cursor, scheme='editor', number_lines=False): """Return a new QTextDocument with highlighting set as HTML textcharformats. The cursor is a cursor of a document.Document instance. If the cursor has a selection, only the selection is put in the new document. If number_lines is True, line numbers are added. """ data = textformats.formatData(scheme) doc = QTextDocument() doc.setDefaultFont(data.font) doc.setPlainText(cursor.document().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document()))) if cursor.hasSelection(): # cut out not selected text start, end = cursor.selectionStart(), cursor.selectionEnd() cur1 = QTextCursor(doc) cur1.setPosition(start, QTextCursor.KeepAnchor) cur2 = QTextCursor(doc) cur2.setPosition(end) cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cur2.removeSelectedText() cur1.removeSelectedText() if number_lines: c = QTextCursor(doc) f = QTextCharFormat() f.setBackground(QColor('#eeeeee')) if cursor.hasSelection(): num = cursor.document().findBlock( cursor.selectionStart()).blockNumber() + 1 last = cursor.document().findBlock(cursor.selectionEnd()) else: num = 1 last = cursor.document().lastBlock() lastnum = last.blockNumber() + 1 padding = len(format(lastnum)) block = doc.firstBlock() while block.isValid(): c.setPosition(block.position()) c.setCharFormat(f) c.insertText('{0:>{1}d} '.format(num, padding)) block = block.next() num += 1 return doc
def indent_line(self, line_no, indent_length): block = self._get_block(line_no) cursor = QTextCursor(block) cursor.joinPreviousEditBlock() cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.MoveAnchor) if indent_length < 0: for i in range(-indent_length): cursor.deleteChar() else: cursor.insertText(" " * indent_length) if indent_length: cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.MoveAnchor) line = unicode(cursor.block().text()) if len(line) and line[0] == " ": cursor.movePosition(QTextCursor.NextWord, QTextCursor.MoveAnchor) self.editview.setTextCursor(cursor) cursor.endEditBlock()
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
def titleATX(self, level): cursor = self.textCursor() text = cursor.block().text() # Are we in a Setext Header? if cursor.block().userState() in [ MS.MarkdownStateSetextHeading1Line1, MS.MarkdownStateSetextHeading2Line1 ]: # Need to remove line below cursor.beginEditBlock() c = QTextCursor(cursor.block().next()) self.selectBlock(c) c.insertText("") self.selectBlock(cursor) cursor.insertText(text) cursor.endEditBlock() return elif cursor.block().userState() in [ MS.MarkdownStateSetextHeading1Line2, MS.MarkdownStateSetextHeading2Line2 ]: cursor.movePosition(QTextCursor.PreviousBlock) self.setTextCursor(cursor) self.titleATX(level) return m = re.match(r"^(#+)(\s*)(.+)", text) if m: pre = m.group(1) space = m.group(2) txt = m.group(3) if len(pre) == level: # Remove title text = txt else: text = "#" * level + space + txt else: text = "#" * level + " " + text self.selectBlock(cursor) cursor.insertText(text)
def html_copy(cursor, scheme='editor', number_lines=False): """Return a new QTextDocument with highlighting set as HTML textcharformats. The cursor is a cursor of a document.Document instance. If the cursor has a selection, only the selection is put in the new document. If number_lines is True, line numbers are added. """ data = textformats.formatData(scheme) doc = QTextDocument() doc.setDefaultFont(data.font) doc.setPlainText(cursor.document().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document()))) if cursor.hasSelection(): # cut out not selected text start, end = cursor.selectionStart(), cursor.selectionEnd() cur1 = QTextCursor(doc) cur1.setPosition(start, QTextCursor.KeepAnchor) cur2 = QTextCursor(doc) cur2.setPosition(end) cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cur2.removeSelectedText() cur1.removeSelectedText() if number_lines: c = QTextCursor(doc) f = QTextCharFormat() f.setBackground(QColor('#eeeeee')) if cursor.hasSelection(): num = cursor.document().findBlock(cursor.selectionStart()).blockNumber() + 1 last = cursor.document().findBlock(cursor.selectionEnd()) else: num = 1 last = cursor.document().lastBlock() lastnum = last.blockNumber() + 1 padding = len(format(lastnum)) block = doc.firstBlock() while block.isValid(): c.setPosition(block.position()) c.setCharFormat(f) c.insertText('{0:>{1}d} '.format(num, padding)) block = block.next() num += 1 return doc
def _append_log(self, record): """Internal method to insert a displayed record into the underlying :class:`QPlainTextEdit`.""" self.infobar.add_record(record) self._rec_lines.append(record.text.count('\n') + 1) # NOTE: For some reason, we must use `setPosition` in order to # guarantee a absolute, fixed selection (at least on linux). It seems # almost if `movePosition(End)` will be re-evaluated at any time the # cursor/selection is used and therefore always point to the end of # the document. cursor = QTextCursor(self.textctrl.document()) cursor.movePosition(QTextCursor.End) pos0 = cursor.position() cursor.insertText(record.text + '\n') pos1 = cursor.position() cursor = QTextCursor(self.textctrl.document()) cursor.setPosition(pos0) cursor.setPosition(pos1, QTextCursor.KeepAnchor) selection = QTextEdit.ExtraSelection() selection.format = self.formats.get(record.domain, self.default_format) selection.cursor = cursor selections = self.textctrl.extraSelections() if selections: # Force the previous selection to end at the current block. # Without this, all previous selections are be updated to span # over the rest of the document, which dramatically impacts # performance because it means that all selections need to be # considered even if showing only the end of the document. selections[-1].cursor.setPosition(pos0, QTextCursor.KeepAnchor) selections.append(selection) self.textctrl.setExtraSelections(selections[-self.maxlen:]) self.textctrl.ensureCursorVisible() if self.maxlen: # setMaximumBlockCount() must *not* be in effect while inserting # the text, because it will mess with the cursor positions and # make it nearly impossible to create a proper ExtraSelection! num_lines = sum(self._rec_lines) self.textctrl.setMaximumBlockCount(num_lines + 1) self.textctrl.setMaximumBlockCount(0)
class Ui_Form( QDialog, ): def __init__(self): super(Ui_Form, self).__init__() loadUi('C:/Users/Manik/PycharmProjects/first/viewDetails.ui', self) self.image = None self.setWindowIcon( QtGui.QIcon("C:/Users/Manik/PycharmProjects/first/1.ico")) self.setWindowTitle("View Details") self.setGeometry(300, 100, 680, 320) self.loadButton.clicked.connect(self.LoadData) self.lineedit1 = QLineEdit(self) self.lineedit1.setPlaceholderText( 'Enter a ID Number to get the details') self.lineedit1.setGeometry(180, 230, 300, 30) self.text = self.lineedit1.text() def LoadData(self): try: conn = mdb.connect('localhost', 'root', '', 'mydatabase') with conn: cur = conn.cursor() cur.execute( """SELECT id,name,dname,age,date,diseasename,medicine from details WHERE id=%s""", (self.lineedit1.text())) self.cursor = QTextCursor(self.textEdit.document()) self.cursor.insertText( str("( ID | Name | Doctor | Age | Apointment | Diseases | Medicines ) " ) + '\n') for i in range(cur.rowcount): result = cur.fetchall() for row in result: #self.cursor = QTextCursor(self.textEdit.document()) self.cursor.insertText(str(row) + '\n') except mdb.Error as e: QMessageBox.about(self, 'Connection', 'Failed to connect') sys.exit(1)
def set_bytes(self, bs): self.pretty_mode = False self.data = bs chunks = HextEditor._split_by_printables(bs) self.clear() cursor = QTextCursor(self.textedit.document()) cursor.beginEditBlock() cursor.select(QTextCursor.Document) cursor.setCharFormat(QTextCharFormat()) cursor.clearSelection() for chunk in chunks: if chr(chunk[0]) in qtprintable: cursor.insertText(chunk.decode()) else: for b in chunk: self._insert_byte(cursor, b) cursor.endEditBlock()
def save(self): """saving of document""" # get file name name = QFileDialog().getSaveFileName(self, 'Save file', filter='*.odt') # write text information from text fields to file doc = QTextDocument() cursor = QTextCursor(doc) cursor.insertTable(self.X, self.Y) for row in self.text_array: for column in row: cursor.insertText(column.text()) cursor.movePosition(QTextCursor.NextCell) writer = QTextDocumentWriter() odf_format = writer.supportedDocumentFormats()[1] writer.setFormat(odf_format) writer.setFileName(name[0]) writer.write(doc)
def log(self, level: LogLevel, text: str) -> None: if level == LogLevel.DEBUG: return old_pos_x = self.horizontalScrollBar().value() old_pos_y = self.verticalScrollBar().value() separator = "" if self._empty else "\n" self.moveCursor(QTextCursor.End) cursor = QTextCursor(self.textCursor()) cursor.insertText(f"{separator}" f"[{level.name.lower()[0]}] " f"[{datetime.datetime.now():%H:%M:%S.%f}] " f"{text}") self.horizontalScrollBar().setValue(old_pos_x if self._scroll_lock else self.verticalScrollBar().minimum()) self.verticalScrollBar().setValue(old_pos_y if self._scroll_lock else self.verticalScrollBar().maximum()) self._empty = False
def write(self, data): cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(data) self.setTextCursor(cursor) self.ensureCursorVisible()
class Log(QTextBrowser): """Widget displaying output from a Job.""" def __init__(self, parent=None): super(Log, self).__init__(parent) self.setOpenLinks(False) self.cursor = QTextCursor(self.document()) self._types = job.ALL self._lasttype = None self._formats = self.logformats() def setMessageTypes(self, types): """Set the types of Job output to display. types is a constant bitmask from job, like job.STDOUT etc. By default job.ALL is used. """ self._types = types def messageTypes(self): """Return the set message types (job.ALL by default).""" return self._types def connectJob(self, job): """Gives us the output from the Job (past and upcoming).""" for msg, type in job.history(): self.write(msg, type) job.output.connect(self.write) def textFormat(self, type): """Returns a QTextFormat() for the given type.""" return self._formats[type] def write(self, message, type): """Writes the given message with the given type to the log. The keepScrolledDown context manager is used to scroll the log further down if it was scrolled down at that moment. If two messages of a different type are written after each other a newline is inserted if otherwise the message would continue on the same line. """ if type & self._types: with self.keepScrolledDown(): changed = type != self._lasttype self._lasttype = type if changed and self.cursor.block().text() and not message.startswith('\n'): self.cursor.insertText('\n') self.writeMessage(message, type) def writeMessage(self, message, type): """Inserts the given message in the text with the textformat belonging to type.""" self.cursor.insertText(message, self.textFormat(type)) @contextlib.contextmanager def keepScrolledDown(self): """Performs a function, ensuring the log stays scrolled down if it was scrolled down on start.""" vbar = self.verticalScrollBar() scrolleddown = vbar.value() == vbar.maximum() try: yield finally: if scrolleddown: vbar.setValue(vbar.maximum()) def logformats(self): """Returns a dictionary with QTextCharFormats for the different types of messages. Besides the STDOUT, STDERR, NEUTRAL, FAILURE and SUCCESS formats there is also a "link" format, that looks basically the same as the output formats, but blueish and underlined, to make parts of the output (e.g. filenames) look clickable. """ textColor = QApplication.palette().color(QPalette.WindowText) successColor = qutil.addcolor(textColor, 0, 128, 0) # more green failureColor = qutil.addcolor(textColor, 128, 0, 0) # more red linkColor = qutil.addcolor(textColor, 0, 0, 128) # more blue stdoutColor = qutil.addcolor(textColor, 64, 64, 0) # more purple s = QSettings() s.beginGroup("log") outputFont = QFont(s.value("fontfamily", "monospace", str)) outputFont.setPointSizeF(s.value("fontsize", 9.0, float)) output = QTextCharFormat() output.setFont(outputFont) # enable zooming the log font size output.setProperty(QTextFormat.FontSizeAdjustment, 0) stdout = QTextCharFormat(output) stdout.setForeground(stdoutColor) stderr = QTextCharFormat(output) link = QTextCharFormat(output) link.setForeground(linkColor) link.setFontUnderline(True) status = QTextCharFormat() status.setFontWeight(QFont.Bold) neutral = QTextCharFormat(status) success = QTextCharFormat(status) success.setForeground(successColor) failure = QTextCharFormat(status) failure.setForeground(failureColor) return { job.STDOUT: stdout, job.STDERR: stderr, job.NEUTRAL: neutral, job.SUCCESS: success, job.FAILURE: failure, 'link': link, }
def _setBlockText(blockIndex, text): cursor = QTextCursor(self._doc.findBlockByNumber(blockIndex)) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) cursor.insertText(text)
def indent_block(block): cursor = QTextCursor(block) indentation = self.__block_indentation(block) cursor.setPosition(block.position() + len(indentation)) cursor.insertText(self.text())