[PyQt] QLineEdit vs. menu keyboard shortcuts

Nathan Weston nathan at genarts.com
Wed Jun 29 18:57:18 BST 2011


On 6/29/2011 1:32 PM, Baz Walter wrote:
> On 29/06/11 18:21, Nathan Weston wrote:
>> On 6/29/2011 1:07 PM, Baz Walter wrote:
>>> as was suggested earlier in this thread, if the line-edit doesn't have
>>> the keyboard focus, it can't trigger its own shortcuts. if it *does*
>>> have the focus, but the shortcut sequence is not one it handles, the
>>> keypress event will be re-propagated (as happens with 'Ctrl+R' in your
>>> example).
>>>
>>> the simplest way to control the focus is to use clearFocus() and
>>> setFocus().
>
>> Unfortunately, I need the line-edit to have keyboard focus (and respond
>> to some keyboard shortcuts), without bashing my global menu shortcuts.
>> It seems like there *should* be a clean way to do this by mucking around
>> with the keyPressEvent, but so far nobody seems to know of one.
>
> did you actually try what was suggested?
>
> going back to your earlier example of dragging in the line-edit to
> change its value: all you need to do is clearFocus() when the drag
> starts and setFocus() when the drag ends. that way, whilst the drag is
> in progress, the line-edit's shortcuts won't work, but your global
> shortcuts will.
>
> if that's not what you want, please try to make it clear what you do
> want (i.e. with a working example).
>

Short answer: focus tricks won't work for me. I need the widget to be 
able to accept keyboard focus and respond to some keyboard shortcuts.

Long answer:
I guess this will require a complete specification of how my widget works.

The widget appears to the user somewhat like a label displaying a 
number. If the user clicks and drags, the value will increase or 
decrease as the mouse is moved. By holding down modifier keys the user 
can adjust the speed with which the value changes.

If the user clicks (but doesn't drag), the number is highlighted and a 
text editing cursor appears. The widget at this point behaves exactly 
like a QLineEdit (with a validator to force numeric values). When the 
user presses Enter or the widget loses focus, it reverts to its default 
appearance.

If the widget has keyboard focus, but isn't in edit mode, the Up/Down 
arrow keys will "nudge" the value a small amount in either direction.

I am implementing this as a subclass of QLineEdit, overriding mouse and 
keyboard events and throwing in some CSS to make it look nice. When the 
widget is in "edit mode" it's set to editable, otherwise it's set to 
non-editable.

Now, when the widget is in its non-editable state, and the user hits 
Ctrl-Z, I want it to trigger the Undo action on the Edit menu. 
Unfortunately, QLineEdit intercepts the Ctrl-Z keystroke and does 
nothing (because it's not editable).

I can't call clearFocus() at the end of the drag, because this would 
break the Up/Down arrow shortcuts.

- Nathan


More information about the PyQt mailing list