PyQt4 拼写检查与语法高亮 [英] PyQt4 Spell Check with syntax highlighter
本文介绍了PyQt4 拼写检查与语法高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在对 QTextEdit() 执行附魔拼写检查时遇到问题.我试试:
I have a problems with implement enchant spell check to QTextEdit(). I try:
from enchant.checker import SpellChecker
chkr = SpellChecker("en_US")
chkr.set_text(self.text.toPlainText())
我不能在 QTextEdit 中使用它?我如何将它与 self.text 一起使用?
And I can`t to use this with QTextEdit? How i can use this with self.text?
推荐答案
如果我正确理解您的问题,您只需要执行以下操作:
If I understand your question correctly you just need to do something like this:
from PyQt4 import QtGui
from enchant.checker import SpellChecker
import re
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.initUI()
def initToolbar(self):
self.spellcheckAction = QtGui.QAction(QtGui.QIcon("icons/logo.png"),"Spellcheck",self)
self.spellcheckAction.setStatusTip("Spell Check document")
self.spellcheckAction.setShortcut("Ctrl+S")
self.spellcheckAction.triggered.connect(self.spellcheckHandler)
self.toolbar = self.addToolBar("Options")
self.toolbar.addAction(self.spellcheckAction)
def initUI(self):
self.text = QtGui.QTextEdit(self)
self.initToolbar()
self.text.setTabStopWidth(33)
self.setCentralWidget(self.text)
self.setGeometry(100,100,1030,800)
self.setWindowTitle("Writer")
self.setWindowIcon(QtGui.QIcon("icons/icon.png"))
def spellcheckHandler(self):
chkr = SpellChecker("en_US")
s = str(self.text.toPlainText())
chkr.set_text(s)
for err in chkr:
self.replaceAll(err.word)
def find(self, query):
text = self.text.toPlainText()
query = r'\b' + query + r'\b'
flags = 0
pattern = re.compile(query,flags)
start = self.lastMatch.start() + 1 if self.lastMatch else 0
self.lastMatch = pattern.search(text,start)
if self.lastMatch:
start = self.lastMatch.start()
end = self.lastMatch.end()
self.moveCursor(start,end)
else:
self.text.moveCursor(QtGui.QTextCursor.End)
def replace(self):
cursor = self.text.textCursor()
if self.lastMatch and cursor.hasSelection():
self.text.setTextBackgroundColor(QtGui.QColor(0,255,0))
self.text.setTextCursor(cursor)
def replaceAll(self, query):
self.lastMatch = None
self.find(query)
while self.lastMatch:
self.replace()
self.find(query)
def moveCursor(self,start,end):
cursor = self.text.textCursor()
cursor.setPosition(start)
cursor.movePosition(QtGui.QTextCursor.Right,QtGui.QTextCursor.KeepAnchor,end - start)
self.text.setTextCursor(cursor)
def main():
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
要获得建议,请使用
chkr.suggest(err.word).
这篇关于PyQt4 拼写检查与语法高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文