[PyQt] QLineEdit vs. menu keyboard shortcuts
apaku at gmx.de
Wed Jun 29 15:34:06 BST 2011
On 29.06.11 09:50:58, Nathan Weston wrote:
> On 6/28/2011 2:17 PM, Hans-Peter Jansen wrote:
> >On Tuesday 28 June 2011, 19:56:35 Nathan Weston wrote:
> >If you're subclassing QLineEdit anyway, what does stop you from
> >overriding keyPressEvent to catch and accept() any unwanted key
> I can certainly do that, but it doesn't cause my QActions to
> trigger. I could intercept specific shortcuts and manually trigger
> the QActions, but then my QLineEdit subclass has to know about all
> the menu items, which is pretty ugly.
> The interaction between QAction shortcuts and widget-specific
> shortcuts is a little strange. I've written a little test program:
> it's a QMainWindow with some menu items and a QLineEdit subclass as
> the central widget.
> The first menu item has Ctrl+R as its shortcut, which doesn't clash
> with anything in QLineEdit. If I type Ctrl+R, the action intercepts
> the keypress event *before* QLineEdit gets it -- I never see a
> The menu item shortcut has Ctrl+Z as a shortcut. If I type Ctrl+Z,
> the QLineEdit gets a keyPressEvent, which causes an undo of the
> text. If I ignore() the event, it disables the undo behavior, but my
> QAction still doesn't fire.
> I've attached my program. If you press Ctrl+Z it will print 'Foo
> keyPress 16777249' (for the Ctrl) and 'Foo keyPress 90' (for the Z).
> If you press Ctrl+R it just prints 'action' from the slot connected
> to my QAction.
> Does anyone understand what's going on under the hood here?
> . . . . . . . . . . . . . . . . . . . . . . . . .
> Nathan Weston nathan at genarts.com
> GenArts, Inc. Tel: 617-492-2888
> 955 Mass. Ave Fax: 617-492-2852
> Cambridge, MA 02139 USA www.genarts.com
> from PyQt4.QtCore import *
> from PyQt4.QtGui import *
> import sys
> class Foo(QLineEdit):
> def keyPressEvent(self, event):
> print 'Foo keyPress', event.key(); sys.stdout.flush()
> QLineEdit.keyPressEvent(self, event)
> app = QApplication()
> window = QMainWindow()
> f = Foo()
> def do_action():
> print 'action'; sys.stdout.flush()
> action1 = QAction('Action 1', f, triggered=do_action)
> action1.setShortcut(Qt.CTRL + Qt.Key_Z)
For actions that should work all over the mainwindow, you should use
More information about the PyQt