本文整理汇总了Python中PyQt4.QtGui.QTextCursor类的典型用法代码示例。如果您正苦于以下问题:Python QTextCursor类的具体用法?Python QTextCursor怎么用?Python QTextCursor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QTextCursor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find
def _find(self, textEdit=None, backward=False):
if textEdit is None:
textEdit = self.textEdit
found = False
if textEdit is not None:
cursor = textEdit.textCursor()
text, flags = self._textAndFindFlags(backward=backward)
position = cursor.position()
cursor = textEdit.document().find(text, cursor, flags)
if not cursor.isNull():
textEdit.setTextCursor(cursor)
found = True
elif self.wrapAroundCheckBox.isChecked():
cursor = QTextCursor(textEdit.textCursor())
cursor.movePosition(backward and QTextCursor.End or QTextCursor.Start)
cursor = textEdit.document().find(text, cursor, flags)
if not cursor.isNull():
if position == cursor.position():
pass #todo
textEdit.setTextCursor(cursor)
found = True
self.writeSettings()
if not found:
QApplication.beep()
self.feedbackLabel.setText(self.tr("Not found"))
else:
self.clearFeedback()
示例2: onMatchNumberChange
def onMatchNumberChange(self, matchNumber):
# Set default format on the whole text before highlighting the selected
# match.
document = self.matchText.document()
cursor = QTextCursor(document)
cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
cursor.setCharFormat(QTextCharFormat())
search = self.getSearchText()
for i, match in enumerate(self.regex.finditer(search)):
if i + 1 == matchNumber:
break
else:
assert False, ("We didn't find a match?! (RE=%r, text=%r" %
(self.regex.pattern, search))
self.formatMatchedText(document, match)
model = self.groupsView.model()
model.clear()
# Create a reversed self.regex.groupindex dictionnary
groupsIndexes = dict((v, k)
for (k, v) in self.regex.groupindex.iteritems())
for i in range(1, self.regex.groups + 1):
groupName = groupsIndexes.get(i, "")
groupValue = match.group(i)
model.append((groupName, groupValue))
示例3: actionTriggered
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
示例4: load
def load(self, keepUndo=False):
"""Loads the current url.
Returns True if loading succeeded, False if an error occurred,
and None when the current url is empty or non-local.
Currently only local files are supported.
If keepUndo is True, the loading can be undone (with Ctrl-Z).
"""
fileName = self.url().toLocalFile()
if fileName:
try:
with open(fileName) as f:
data = f.read()
except (IOError, OSError):
return False # errors are caught in MainWindow.openUrl()
text = util.decode(data)
if keepUndo:
c = QTextCursor(self)
c.select(QTextCursor.Document)
c.insertText(text)
else:
self.setPlainText(text)
self.setModified(False)
self.loaded()
app.documentLoaded(self)
return True
示例5: articulation_positions
def articulation_positions(cursor):
"""Returns a list of positions where an articulation can be added.
Every position is given as a QTextCursor instance.
If the cursor has a selection, all positions in the selection are returned.
"""
c = lydocument.cursor(cursor)
if not cursor.hasSelection():
# just select until the end of the current line
c.select_end_of_block()
rests = True
partial = ly.document.OUTSIDE
else:
rests = False
partial = ly.document.INSIDE
positions = []
for item in ly.rhythm.music_items(c, partial):
if not rests and item.tokens and isinstance(item.tokens[0], ly.lex.lilypond.Rest):
continue
csr = QTextCursor(cursor.document())
csr.setPosition(item.end)
positions.append(csr)
if not cursor.hasSelection():
break # leave if first found, that's enough
return positions
示例6: drawContents
def drawContents(self, painter):
"""
Reimplementation of drawContents to limit the drawing
inside `textRext`.
"""
painter.setPen(self.__color)
painter.setFont(self.font())
if self.__textRect:
rect = self.__textRect
else:
rect = self.rect().adjusted(5, 5, -5, -5)
if Qt.mightBeRichText(self.__message):
doc = QTextDocument()
doc.setHtml(self.__message)
doc.setTextWidth(rect.width())
cursor = QTextCursor(doc)
cursor.select(QTextCursor.Document)
fmt = QTextBlockFormat()
fmt.setAlignment(self.__alignment)
cursor.mergeBlockFormat(fmt)
painter.save()
painter.translate(rect.topLeft())
doc.drawContents(painter)
painter.restore()
else:
painter.drawText(rect, self.__alignment, self.__message)
示例7: cursors
def cursors(self):
"""Cursors for rectangular selection.
1 cursor for every line
"""
cursors = []
if self._start is not None:
startLine, startVisibleCol = self._start
currentLine, currentCol = self._qpart.cursorPosition
if abs(startLine - currentLine) > self._MAX_SIZE or \
abs(startVisibleCol - currentCol) > self._MAX_SIZE:
# Too big rectangular selection freezes the GUI
self._qpart.userWarning.emit('Rectangular selection area is too big')
self._start = None
return []
currentBlockText = self._qpart.textCursor().block().text()
currentVisibleCol = self._realToVisibleColumn(currentBlockText, currentCol)
for lineNumber in range(min(startLine, currentLine),
max(startLine, currentLine) + 1):
block = self._qpart.document().findBlockByNumber(lineNumber)
cursor = QTextCursor(block)
realStartCol = self._visibleToRealColumn(block.text(), startVisibleCol)
realCurrentCol = self._visibleToRealColumn(block.text(), currentVisibleCol)
if realStartCol is None:
realStartCol = block.length() # out of range value
if realCurrentCol is None:
realCurrentCol = block.length() # out of range value
cursor.setPositionInBlock(min(realStartCol, block.length() - 1))
cursor.setPositionInBlock(min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor)
cursors.append(cursor)
return cursors
示例8: spanner_positions
def spanner_positions(cursor):
"""Return a list with 0 to 2 QTextCursor instances.
At the first cursor a starting spanner item can be inserted, at the
second an ending item.
"""
c = lydocument.cursor(cursor)
if cursor.hasSelection():
partial = ly.document.INSIDE
else:
# just select until the end of the current line
c.select_end_of_block()
partial = ly.document.OUTSIDE
items = list(ly.rhythm.music_items(c, partial=partial))
if cursor.hasSelection():
del items[1:-1]
else:
del items[2:]
positions = []
for i in items:
c = QTextCursor(cursor.document())
c.setPosition(i.end)
positions.append(c)
return positions
示例9: highlightMarkdown
def highlightMarkdown(self, text, strt):
cursor = QTextCursor(self.document())
bf = cursor.blockFormat()
self.setFormat(0, len(text), QColor(self.theme['color']))
#bf.clearBackground()
#cursor.movePosition(QTextCursor.End)
#cursor.setBlockFormat(bf)
#Block quotes can contain all elements so process it first
self.highlightBlockQuote(text, cursor, bf, strt)
#If empty line no need to check for below elements just return
if self.highlightEmptyLine(text, cursor, bf, strt):
return
#If horizontal line, look at pevious line to see if its a header, process and return
if self.highlightHorizontalLine(text, cursor, bf, strt):
return
if self.highlightAtxHeader(text, cursor, bf, strt):
return
self.highlightList(text, cursor, bf, strt)
self.highlightLink(text, cursor, bf, strt)
self.highlightImage(text, cursor, bf, strt)
self.highlightCodeSpan(text, cursor, bf, strt)
self.highlightEmphasis(text, cursor, bf, strt)
self.highlightBold(text, cursor, bf, strt)
self.highlightCodeBlock(text, cursor, bf, strt)
示例10: postImport
def postImport(self, settings, doc):
"""Adaptations of the source after running musicxml2ly
Present settings:
Reformat source
Remove superfluous durations
Remove duration scaling
Engrave directly
"""
cursor = QTextCursor(doc)
if settings[0]:
import reformat
reformat.reformat(cursor)
if settings[1]:
cursor.select(QTextCursor.Document)
from rhythm import rhythm
rhythm.rhythm_implicit_per_line(cursor)
if settings[2]:
cursor.select(QTextCursor.Document)
from rhythm import rhythm
rhythm.rhythm_remove_fraction_scaling(cursor)
if settings[3]:
import engrave
engrave.engraver(self.mainwindow()).engrave("preview", doc, False)
示例11: load
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 make 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)
self.loaded()
app.documentLoaded(self)
示例12: cursorAt
def cursorAt(self, position, in_active_area=True):
c = QTextCursor(self.block)
p = min(position, self.length-1)
if in_active_area:
p = max(p, self.active_area_start)
c.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, p)
return c
示例13: goto_target
def goto_target(mainwindow, target):
"""Switch to the document and location where the node target is."""
filename = target.document.filename
doc = app.openUrl(QUrl.fromLocalFile(filename))
cursor = QTextCursor(doc)
cursor.setPosition(target.position)
browseriface.get(mainwindow).setTextCursor(cursor)
mainwindow.currentView().centerCursor()
示例14: _makeQtExtraSelection
def _makeQtExtraSelection(startAbsolutePosition, length):
selection = QTextEdit.ExtraSelection()
cursor = QTextCursor(self.document())
cursor.setPosition(startAbsolutePosition)
cursor.setPosition(startAbsolutePosition + length, QTextCursor.KeepAnchor)
selection.cursor = cursor
selection.format = self._userExtraSelectionFormat
return selection
示例15: main
def main():
"""Main function."""
options, files = parse_commandline()
urls = list(map(url, files))
if not app.qApp.isSessionRestored():
if not options.new and remote.enabled():
api = remote.get()
if api:
api.command_line(options, urls)
api.close()
sys.exit(0)
if QSettings().value("splash_screen", True) not in ("false", False):
import splashscreen
splashscreen.show()
QTimer.singleShot(0, remote.setup) # Start listening for IPC
import mainwindow # contains MainWindow class
import session # Initialize QSessionManager support
import sessions # Initialize our own named session support
import document # contains Document class
# boot Frescobaldi-specific stuff that should be running on startup
import viewhighlighter # highlight arbitrary ranges in text
import matcher # matches braces etc in active text window
import progress # creates progress bar in view space
import autocomplete # auto-complete input
if app.qApp.isSessionRestored():
# Restore session, we are started by the session manager
session.restoreSession()
return
# load specified session
doc = None
if options.session and options.session != "none":
doc = sessions.loadSession(options.session)
# Just create one MainWindow
win = mainwindow.MainWindow()
win.show()
if urls:
for u in urls:
doc = win.openUrl(u, options.encoding)
elif not options.session:
# no docs, load default session
doc = sessions.loadDefaultSession()
win.setCurrentDocument(doc or document.Document())
if urls and options.line is not None:
# set the last loaded document active and apply navigation if requested
pos = doc.findBlockByNumber(options.line - 1).position() + options.column
cursor = QTextCursor(doc)
cursor.setPosition(pos)
win.currentView().setTextCursor(cursor)
win.currentView().centerCursor()