[PyQt] Problem when trying to setFocus() on QLineEdit

Gabriel Reis gabrielcnr at gmail.com
Fri Mar 11 09:52:53 GMT 2011

Hello everybody,

In my PyQt4 application I have a main window with a QDockWidget which
contains a widget composed by a QLineEdit and a QTreeView, which is used to
launch the windows in the application.

I also have a QAction, with a global application shortcut, associated to the
QLineEdit mentioned before. The intention here is as the user starts to open
multiple windows he will be using this shortcut to bring the launcher dock
widget to front and have the keyboard focus set to the QLineEdit, making the
navigation easier.

The problem I am having is when I hit the shortcut from another window in
the application it brings me the main window and the dock widget to front,
but it doesn't set focus to the QLineEdit. I have tried different possible
solutions without success so far. The issue with the parenthood chain seems
to be resolved, since the qApp.activeWindow() is the main window and it is
parent of the QDockWidget which in its turn is the parent of the
QLineWidget's parent. I also tried to obtain the previously focused widget
and clear its focus, before setting focus to the QLineEdit. I also tried to
play up with the focus reasons and even tried to simulate the mouse click
event in the area of the QLineEdit. Unfortunately I haven't had the luck to
get it working in any way.

Here is the code snippet of the action callback:


def on_action_search_triggered(self):
    print 'inside the callback'

    from bbm.main_window import MainWindow
    main_window = MainWindow.get_singleton()

    focused_widget = qApp.focusWidget()


    print self.ed_search.parent().parent().parent()
    print qApp.activeWindow()

    print qApp.focusWidget()


You can see still on the code snippet above that I am still trying to force
the application to give the focus the QLineEdit I want. But when that code
gets to be executed I got the following output:

inside the callback
<bbm.main_window.MainWindow object at 0x2d52830>
<bbm.main_window.MainWindow object at 0x2d52830>

Note in the end the 'None' means that none widget currently is focused in
the application.

I couldn't find a solution for this on Google, StackOverflow, etc. Can
anybody please turn on the lights? :-)

Thank you very much for your attention.

Kindest regards,

Gabriel Reis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20110311/bc052f15/attachment.html>

More information about the PyQt mailing list