[PyQt] QWidget focusInEvent() ?

Mark Summerfield mark at qtrac.eu
Thu May 29 17:30:10 BST 2008


On 2008-05-29, B Clowers wrote:
> I have what would seem to be a fairly small problem.  My
> application has a main window that currently has the ability to spawn
> a number of Non-Modal QWidgets in their own respective windows. 
> I need to emit or catch a signal that is produced whenever a
> particular QWidget in its own window gets the focus.  After
> looking at the documentation I can't seem to find a particular signal
> that is emitted.  Does anyone have an idea how to accomplish this
> task?

It isn't quite so simple because focus is not a high level abstract
behaviour which signals and slots are for, but a low level detail. So
I think you'll have to use the event handling mechanism.

Here's something that works for me on Linux, i.e., if I run it as soon
as it appears it prints "got the focus", then if I Alt+Tab to another
window and then back it prints it again:


import sys
from PyQt4 import QtGui, QtCore

class EventFilter(QtCore.QObject):

    def __init__(self, parent=None):
	QtCore.QObject.__init__(self, parent)

    def eventFilter(self, obj, event):
	if event.type() == QtCore.QEvent.ActivationChange:
	    if self.parent().isActiveWindow():
		print "got the focus"
	return QtCore.QObject.eventFilter(self, obj, event)
	

class TestWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

	self.installEventFilter(EventFilter(self))

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Test Widget')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'),
            QtGui.qApp, QtCore.SLOT('quit()'))
        
     
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    tw = TestWidget()
    tw.show()
    sys.exit(app.exec_())


-- 
Mark Summerfield, Qtrac Ltd., www.qtrac.eu



More information about the PyQt mailing list