2
votes

So, i have a function, which aim is to color words if they are surrounded by commas.

    def __init__(...something):
        ...something
        self.user_input = QtGui.QTextEdit(self)
        self.user_input.textChanged.connect(self.check_text)
        ...something

    def check_text(self):
        text = self.user_input.toPlainText().strip()
        comma = ","
        if comma in text: 
            elements_quantity = text.count(comma)
            sites = text.split(comma)
            sites_quantity = len(sites)
            done_sites = [] 
            if sites_quantity > elements_quantity:
                done_sites = sites[:elements_quantity]
            else:
                done_sites = sites
        else:
            done_sites = [""]

        for site in done_sites:
            new_site = "<strong>{site}</strong>"
            text = text.replace(site, new_site.format(site=site))
        self.user_input.setHtml(text)
        self.user_input.moveCursor(QtGui.QTextCursor.End)

And, when I start writing, I have RecursionError: maximum recursion depth exceeded while calling a Python object each time I write a symbol. What I should to do to improve it?

1
you should not update user_input in check_text, because each time you call setHtml (or moveCursor) it emits signal ` textChanged ` and you are again in check_text method with the text you just edited. If you need to update text that way - disconnect signal before writing and connect again after. - Gennady Kandaurov

1 Answers

1
votes

Just block signals when you try to change the text

self.blockSignal(True)
self.user_input.setHtml(text)
self.user_input.moveCursor(QtGui.QTextCursor.End)
self.blockSignal(False)