7

I have a QPlainTextEdit and want to process the content when it loses focus. I've seen that I can either do this with the focusChanged event or with the focusOutEvent virtual function.

I don't know how to pass parameters with the new syntax (i.e. my_app.focusChanged.connect(my_handler) where my_handler is a locally defined function). So I tried working with the virtual function.

Since the interface is created with QT Designer inheriting QPlainTextEdit would be an overkill, so I tried to override the virtual function by simply using my_text_edit.focusOutEvent = my_handler. This did intercept the message as I wanted, but it apparently overwrote some built in functionality in QPlainTextEdit and I get artefacts - namely the cursor from the text edit does not disappear when it looses focus. I figured that I should somehow call the original event and what worked for me was the following:

In my __init__ method I have:

    self.original_handler = self.my_text_edit.focusOutEvent
    self.my_text_edit.focusOutEvent = self.my_handler

The definition of my_handler is:

    def my_handler(self, event):
        self.original_handler(event)
        # my own handling follows...

I am basically replicating what I expect the library to do for me. I find this too clumsy and I can see how it can backfire in many ways during maintenance. Can anyone suggest a neater way to do it? Thanks!

1
  • This is the way I do it, so I am also interested in any responses.
    – derricw
    Sep 24, 2014 at 16:40

1 Answer 1

12

UPDATE:

The original answer below mostly relates to PySide/PyQt4, and is partly out of date - so I have now added a PySide2/PyQt5 demo that implements event-handlers, event-filters and global signals. The final section on widget promotion is still valid, though, and is well-worth considering if you're using Qt Designer.

PySide2/PyQt5:

from PySide2 import QtCore, QtWidgets
# from PyQt5 import QtCore, QtWidgets

class PlainTextEdit(QtWidgets.QPlainTextEdit):
    def focusInEvent(self, event):
        print('event-focus-in:', self.objectName())
        super().focusInEvent(event)

    def focusOutEvent(self, event):
        print('event-focus-out:', self.objectName())
        super().focusOutEvent(event)

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.textEdit = PlainTextEdit(objectName='textEdit')
        self.dateEdit = QtWidgets.QDateEdit(objectName='dateEdit')
        self.button = QtWidgets.QPushButton('Test', objectName='button')
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.textEdit)
        layout.addWidget(self.dateEdit)
        layout.addWidget(self.button)
        self.dateEdit.installEventFilter(self)
        QtWidgets.QApplication.instance().focusObjectChanged.connect(
            self.handleFocusChange)

    def handleFocusChange(self, source):
        print(f'signal-focus-in:', source.objectName())

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.FocusIn:
            print('filter-focus-in:', source.objectName())
        elif event.type() == QtCore.QEvent.FocusOut:
            print('filter-focus-out:', source.objectName())
        return super().eventFilter(source, event)

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    app.exec_()

PySide/PyQt4:

Personally, I never use the monkey-patching style of overriding virtual methods, but the correct way to retain the original behaviour would be to call the base-class method directly, like this:

def my_handler(self, event):
    QtGui.QPlainTextEdit.focusOutEvent(self.my_text_edit, event)
    # my own handling follows...

I don't understand why you can't use the focusChanged signal, though. The handler for it would simply be:

def my_handler(self, old, new):
    if old is self.my_text_edit:
        print('focus out')
    elif new is self.my_text_edit:
        print('focus in')

However, my own preference would be to use an event filter:

class Window(QtGui.QMainWindow)
    def __init__(self):
        ...
        self.my_text_edit.installEventFilter(self)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.FocusOut and
            source is self.my_text_edit):
            print('eventFilter: focus out')
            # return true here to bypass default behaviour
        return super(Window, self).eventFilter(source, event)

This is a much more flexible solution, which provides a generic way to handle any event type for any widget that has been imported via Qt Designer (or, in fact, any widget that you just don't want to subclass).


Widget Promotion:

There is also the possibility of widget promotion, which can be used to directly replace the widgets in generated ui modules with your own subclasses. This would then allow you to override any virtual methods via inheritance, rather than monkey-patching individual instances. If you are importing several widgets of the same type from Qt Designer which share a lot of custom functionality, this can provide a very clean solution.

A simple explanation of how to do widget promotion in PyQt can be found in my answer to: Replace QWidget objects at runtime.

5
  • As I mentioned in the question my problem with the focusChanged signal is that I don't know what the syntax is to register it. How do I pass the two widget parameters (see the second paragraph of the question)?
    – mapto
    Sep 25, 2014 at 13:58
  • @mapto. I don't know what you mean by "register it". The signal is emitted by the QApplication, which will automatically send the correct parameters - all you need to do is connect an appropriate handler to it. If you want to emit the signal yourself, you could do my_app.focusChanged.emit(old, new). But I can't see anything in your question that suggests why you would need to do this. Have you actually tried any of the solutions in my answer? If so, why exactly aren't they working for you?
    – ekhumoro
    Sep 25, 2014 at 19:30
  • I have called the base-line method as you have suggested and it worked for me. I have also implemented the event filter and it also worked.
    – mapto
    Sep 26, 2014 at 14:42
  • Yet, because of consistency with my other callbacks my preference would have been to use singals. By "register it" I mean exactly the same as what you mean by "connect an appropriate handler to it". Probably the confusion comes from the fact that I have provided an example of what does not work for me. I cannot figure out what to put instead of my_app in the line my_app.focusChanged.connect(my_handler). I've tried with my QApplication and QWidget containers and this throws AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect'
    – mapto
    Sep 26, 2014 at 14:43
  • 1
    @mapto. The application instance can be accessed via QtGui.qApp. So try QtGui.qApp.focusChanged.connect(my_handler).
    – ekhumoro
    Sep 26, 2014 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.