Как стать автором
Обновить

Комментарии 1

Достаточно забавно что я делал такую-же штуку вот буквально на прошлой неделе, только на python. Т.к. там нет прямого доступа к hunspell, то работает оно через enchant и с самопальным простейшим токенизером, если проверять английский то можно использовать встроенный токенизер enchant. Если вдруг кому надо, делюсь:
# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import enchant
import re

def findWord(text, pos):
    words = re.split('(\W+)', text)
    idx = 0
    for w in words:
        if pos >= idx and pos < (idx + len(w)):
            return w, idx, len(w)
        idx += len(w)
    return None, -1, 0

class Highlighter(QSyntaxHighlighter):
    def __init__(self, arg):
        QSyntaxHighlighter.__init__(self, arg.document())
        self.textEdit = arg
        arg.customContextMenuRequested.connect(self.contextMenu)
        self.dic = enchant.Dict("ru_RU")

    def highlightBlock(self, text):
        if len(text) == 0:
            return
        words = re.split('(\W+)', text)
        idx = 0
        fmt = QTextCharFormat()
        fmt.setUnderlineColor(QColor(255, 0, 0))
        fmt.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
        for w in words:
            if re.match('\w', w) and not(self.dic.check(w)):
                self.setFormat(idx, len(w), fmt)
            idx += len(w)

    def contextMenu(self, pt):
        cursor = self.textEdit.textCursor()
        word = None
        if not(cursor.hasSelection()):
            text = self.textEdit.toPlainText()
            word, p, i = findWord(text, cursor.position())
        menu = self.textEdit.createStandardContextMenu()
        if word:
            fa = menu.actions()[0]
            sl = self.dic.suggest(word)
            if len(sl) == 0:
                none = QAction("(none)", self)
                none.setEnabled(False)
                menu.insertAction(fa, none)
            for s in sl:
                a = QAction(s, self)
                a.triggered.connect(lambda b, r=s: self.replaceWord(r))
                menu.insertAction(fa, a)
            menu.insertSeparator(fa)
        gp = self.textEdit.mapToGlobal(pt)
        menu.exec_(gp)

    def replaceWord(self, rep):
        cursor = self.textEdit.textCursor()
        text = self.textEdit.toPlainText()
        word, p, i = findWord(text, cursor.position())
        cursor.beginEditBlock()
        cursor.setPosition(p)
        cursor.setPosition(p + i, QTextCursor.KeepAnchor)
        cursor.removeSelectedText()
        cursor.insertText(rep)
        cursor.endEditBlock()


Использование очень простое, просто нужно создать и хранить где-то объект параметром передав ему QTextEdit.
Зарегистрируйтесь на Хабре, чтобы оставить комментарий

Публикации