python-2.7pyqt4mouseoversignals-slotsqlineedit

QLineEdit hover-over Signal - when mouse is over the QlineEdit


I have a QLineEdit, and I need to know if there is a signal which can track mouse hover over that QLineEdit, and once mouse is over that QLineEdit it emits a signal.

I have seen the documents, and found we have the following signals:

cursorPositionChanged ( int old, int new )
editingFinished ()
returnPressed ()
selectionChanged ()
textChanged ( const QString & text )
textEdited ( const QString & text )

However, none of this is exactly for hover-over. Can you suggest if this can be done by any other way in PyQt4?


Solution

  • There is no built-in mouse-hover signal for a QLineEdit.

    However, it is quite easy to achieve something similar by installing an event-filter. This technique will work for any type of widget, and the only other thing you might need to do is to set mouse tracking (although this seems to be switched on by default for QLineEdit).

    The demo script below show how to track various mouse movement events:

    from PyQt4 import QtCore, QtGui
    
    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)
            self.edit = QtGui.QLineEdit(self)
            self.edit.installEventFilter(self)
            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.edit)
    
        def eventFilter(self, source, event):
            if source is self.edit:
                if event.type() == QtCore.QEvent.MouseMove:
                    pos = event.globalPos()
                    print('pos: %d, %d' % (pos.x(), pos.y()))
                elif event.type() == QtCore.QEvent.Enter:
                    print('ENTER')
                elif event.type() == QtCore.QEvent.Leave:
                    print('LEAVE')
            return QtGui.QWidget.eventFilter(self, source, event)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 300, 300, 100)
        window.show()
        sys.exit(app.exec_())