本文整理汇总了Python中PyQt5.QtGui.QTextCursor.insertText方法的典型用法代码示例。如果您正苦于以下问题:Python QTextCursor.insertText方法的具体用法?Python QTextCursor.insertText怎么用?Python QTextCursor.insertText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtGui.QTextCursor
的用法示例。
在下文中一共展示了QTextCursor.insertText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
示例2: actionTriggered
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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
示例3: setLine
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
示例4: append
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
def append(self, text):
"""Append line to the end
"""
cursor = QTextCursor(self._doc)
cursor.movePosition(QTextCursor.End)
cursor.insertBlock()
cursor.insertText(text)
示例5: insert_snippet
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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
示例6: cut_assign
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
示例7: write
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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()
示例8: apply_changes
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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
示例9: insert
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
示例10: indent_line
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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()
示例11: html_copy
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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
示例12: cmdJoinLines
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
示例13: Log
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
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)
#.........这里部分代码省略.........
示例14: indent_block
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
def indent_block(block):
cursor = QTextCursor(block)
indentation = self.__block_indentation(block)
cursor.setPosition(block.position() + len(indentation))
cursor.insertText(self.text())
示例15: _setBlockText
# 需要导入模块: from PyQt5.QtGui import QTextCursor [as 别名]
# 或者: from PyQt5.QtGui.QTextCursor import insertText [as 别名]
def _setBlockText(blockIndex, text):
cursor = QTextCursor(self._doc.findBlockByNumber(blockIndex))
cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
cursor.insertText(text)