pythonpyqtpyqt4pyqt5qwidget

How to know which qwidget in a ui form got the focus in pyqt


I am new to PyQt. I designed a form in QtDeveloper which have three controls. One push button, one combo box and one line edit. The name of the line edit widget in my ui form is myLineEdit. I want to know which Qwidget got focus (QLineEdit or QComboBox). I implement the code obtained from internet. When the code run, a separate line edit is created and it works fine. But I want to give the focusInEvent to myLineEdit widget created in the .ui form. My code is given. Please help.

class MyLineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)
    def focusInEvent(self, event):
        print 'focus in event'
        self.clear()
        QLineEdit.focusInEvent(self, QFocusEvent(QEvent.FocusIn))

class MainWindow(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.myLineEdit = MyLineEdit(self)

Solution

  • You must implement the eventFilter method and enable this property to the widgets that are needed with:

    {your widget}.installEventFilter(self)
    

    The eventFilter method has as information the object and type of event.

    Example

    import sys
    from PyQt5 import uic
    from PyQt5.QtCore import QEvent
    from PyQt5.QtWidgets import QApplication, QWidget
    
    uiFile = "widget.ui"  # Enter file here.
    
    Ui_Widget, _ = uic.loadUiType(uiFile)
    
    
    class Widget(QWidget, Ui_Widget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent=parent)
            self.setupUi(self)
            self.lineEdit.installEventFilter(self)
            self.pushButton.installEventFilter(self)
            self.comboBox.installEventFilter(self)
    
        def eventFilter(self, obj, event):
            if event.type() == QEvent.FocusIn:
                if obj == self.lineEdit:
                    print("lineedit")
                elif obj == self.pushButton:
                    print("pushbutton")
                elif obj == self.comboBox:
                    print("combobox")
            return super(Widget, self).eventFilter(obj, event)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here

    Ouput:

    lineedit
    pushbutton
    combobox
    pushbutton
    lineedit