Access the built-in shortcuts of PyQt5 components? - python

I'm very keen on being able to use the keyboard to do everything with a GUI and am currently exploring QTreeView and QTableView among other things.
I'm adding a lot of my own hotkeys (shortcuts) and am devising a method to automate a user list or guide to these available hotkeys.
But something like QTreeView also comes with its own built-in hotkeys, e.g. arrow keys for navigation, F2 to start editing, Ctrl-A for "select all", etc.. I want to get a comprehensive list of these and include them in the automatically generated user guide.
I've got to this page, for example, but I haven't really got a clue how to dig down into PyQt5 components to unearth this kind of information programmatically.
There's some interesting functionality, probably unknown to many users, with QTreeView: e.g. if, in column 0, you have a tree structure you can skip from label (text) to label by pressing the first letter of each one's label. But if you enter 2 (or more) keys quickly enough this also works: entering "ra" will skip over "Roma" and "Rimini" to "Ravenna" even if "Roma" and "Rimini" come first. It turns out that this is implemented by QTreeView.keyboardSearch ... but what I want to know is whether it's possible to find details of the "mapping" functionality for this and other keyboard enablements, often implemented by keyPressEvent, programmatically. Having looked a little at the PyQt5 files it seems that a lot of PyQt5 functionality may ultimately be contained in .dll files (this is a W10 machine), so I'm not particularly optimistic.

Each widget has a certain behavior depending on the hotkeys pressed, so there is no documentation that indicates all the cases, so you will have to review the documentation of each class and the parent class. So for example to understand the behavior of QTableView you should also review the documentation of QAbstractItemView, QAbstractScrollArea and QFrame (the same is for QTreeView), considering the above we can collect information:
void QAbstractScrollArea::keyPressEvent(QKeyEvent *e)
This function is called with key event e when key presses occur. It
handles PageUp, PageDown, Up, Down, Left, and Right, and ignores all
other key presses.
QAbstractItemView:
void QAbstractItemView::keyPressEvent(QKeyEvent *event).
This function is called with the given event when a key event is sent
to the widget. The default implementation handles basic cursor
movement, e.g. Up, Down, Left, Right, Home, PageUp, and PageDown; the
activated() signal is emitted if the current index is valid and the
activation key is pressed (e.g. Enter or Return, depending on the
platform). This function is where editing is initiated by key press,
e.g. if F2 is pressed.
(emphasis mine)
QTableView and QTreeView when inheriting from QAbstractItemView have the same hotkeys.

Related

How to use "on edit" events/signals with e.g. QLineEdit in pyside6 (Qt6)

Sorry for this post but I still don't get it after my research on the internet.
I am using Python PySide6 since I need to due to some display scaling issues I have with PyQt6 and other older versions.
I already have implemented the basics of a large program with dynamic .ui loading and now I want to implement the event actions for all my gui elements. Some I already managed to use by overloading the eventFilter method of the gui objects by using installEventFilter(self) function. That works well for hovering and other things and the used events are always of the type QtCore.QEvent. .... The problem is that I am missing some events here.
First an easy example and maybe the potential solution explains it for all other cases in my code:
How can I implement a function for the "on change" event of an QLineEdit object? I just want to get notified when the value of the control has been changed.
On the internet I find documentation for signals that should be connected to a slot that I can implement myself.
For example:
self.any_line_edit.textChanged.connect(self.any_slot)
The strange thing is, my QLineEdit object seems to have no reference for the "textChanged" signal. At least PyCharm is not able to resolve the name and I see the other methods of the QLineEdit class so the type of the object seems to be fine.
On other websites I find a similar example for QPushButton:
self.button.clicked.connect(self.the_button_was_clicked)
Same problem here. My PySide6 QPushButton seem to have no signal called "clicked".
Then I thought, no problem. Maybe I just continue using the eventFilter overload function and just install and replace the eventFilter for every object and manually filter the needed event myself.
But it seems that a simple QLineEdit throws no event that equals an "on edit" functionality.
I just see events like: QEvent::Paint, QEvent::DynamicPropertyChange, QEvent::WindowDeactivate, QEvent::Leave and many others but nothing like "on edit" or "edit end" or "on changed" or something.
So it seems that I don't see a respective event in the eventFilter function and due to any circumstance I also don't see the signals used to connect the Object to Slots.
I am sure I am missing something very basic but currently I am really confused.
I am using Python 3.9, PySide6 and PyCharm 2022.1 .
I just want to get notified if these input controls are getting changed in their values. I even have more complex signal-slot constructs and eventFilter reimplementations in my code and now I fail on such a basic thing. To my excuse: Normally I am implementing in Qt5 with C++ so I am a noob regarding Python and PySide6. xD
There is no such "on edit" event. The reason is that events are not meant for that. As the documentation explains:
In Qt, events are objects, derived from the abstract QEvent class, that represent things that have happened either within an application or as a result of outside activity that the application needs to know about. Events can be received and handled by any instance of a QObject subclass, but they are especially relevant to widgets.
So, events are "generic", not specialized for any widget or object type.
An "on edit" event would make sense only for editable widgets (which are just a few: QLineEdit, QPlainTextEdit, QTextEdit and their derived classes), and such an event would be also too generic and abstract to justify its existence.
Most importantly, events are normally created by Qt and then "sent" to the objects that could and possibly should handle them; again, from the above docs:
When an event occurs, Qt creates an event object to represent it by constructing an instance of the appropriate QEvent subclass, and delivers it to a particular instance of QObject (or one of its subclasses) by calling its event() function.
Note: some events are "synthetic", generated internally by Qt when required, sometimes even by widgets: in some cases, it's to work around some OS specific issues in complex focus situations, others due to the architecture of a particular framework (such as the Graphics View, which uses an internal "graphics event" system for items).
Qt cannot know (nor should) if the target object(s) is "editable". That's also because events are normally propagated from the target object up to the object tree, going up through all its parents, until the event is actually handled or (at least) accepted. That is of utmost importance for the event system: especially with input events, those events are intended for generic use by any object in the widget structure, so a widget (instance) specific "on edit" event wouldn't make any sense, mostly because it would be an event that would be only used by the widget itself.
In fact, some similar events do exist (such as QInputEvent, or the more specific QKeyEvent), but, as the name suggests, they are input events, they do not tell with certainty that the event actually results in an edit.
When the user presses a key, Qt creates a QKeyEvent and sends it to the currently focused widget. If that widget accepts that event, that event is (normally) not processed anymore by anything else. If the widget does not accept it, Qt will then propagate the event to its parent, which will decide if accept it in turn or not, and so on up to the top level window.
Note: events can be handled (or not) and accepted (or ignored). This means that a widget could handle (do "something" with that event) and still ignore it. A typical example is the Tab key: a QLineEdit would handle it in the sense that it will check that event, and then ignore it; then that event will be managed by its parent which possibly use it to switch the focus to the next widget that accepts it. A QTextEdit, instead, will both handle and accept the event, as it will normally write a tabulation character in the document contents.
In summary, an event is dispatched to a specific designated object and generally only handled by the single object that actually accepts it.
Signals, on the other hand, are a "communication system" that follows the observer pattern, similarly to the callback mechanism: you "subscribe" to a certain signal and whenever the object emits that signal, the receiver will do anything it wants. The eventual argument(s) of that signal is not changed (or, at least, it shouldn't), and the subscriber(s) can be anything. The sender of that signals doesn't need to care about the targets, nor the different "hierarchy" of those objects matters, as opposed to events.
In summary, don't use events for this, use signals, as that's what they've been made for. This is completely fine:
self.any_line_edit.textChanged.connect(self.any_slot)
Finally, the warnings you're getting from PyCharm are just that: warnings (which are not errors). When the UI is dynamically loaded on runtime, the IDE cannot know the object types of the new attributes, because they will be effective only when the program is running.
In fact, the object to which the attribute is referencing could also change during the lifespan of the program: imagine a class that sets an instance attribute for a "target" widget that is used as an argument in its __init__. How could the IDE know if that widget is a QLineEdit or a QPushButton and "accept" the attributes of that specific widget, such as textChanged or clicked? It couldn't.
So, dynamically created attributes will always show that warning; and you can safely ignore them, as annoying as they are (there should be some shortcut to do that, AFAIK).

Make widget treat numpad arrows the same way as the other arrow keys

I first noticed this when I was using IDLE for a task, but it shows up in my own tkinter programs as well. There are two sets of arrow keys on many keyboards, the regular arrow keys that are often next to the spacebar row, and the arrow keys on the key pad, which double as number entry keys when numlock is turned on. In tkinter the two sets produce different event names when pressed.
My issue is that when using various built in tkinter widgets, such as Text, and Entry, the default tkinter behaviour appears to be to ignore the key pad events. I would like to have my program treat both sets the same.
I am hoping that there is a relatively simple method of accomplishing this, such as setting a variable in the module after I import it, or binding the KP_* events to functions which then emit corresponding regular arrow key events back to my widgets. However the only thing I have found that even acknowledges the existence of this quirk is this other, unanswered, Stack Overflow question.
So after digging around some more I created this function to forward events to another event name. It probably has a number of potential improvements, but this is the general idea.
The function is called on the widget that you want to remap events for, calling it on the root widget will remap events for at least all other widgets that haven't been bound to anything else.
One can change which events are translated to which other events using the kmap variable. If you do, be sure you don't have any loops in your forwarding, this function does zero sanity checking.
I have only copied the modifier key state from the original event here, since that was enough for it to do what I wanted, but in some circumstances you could need to copy more information.
I found the key event information from the link in the Python docs for tkinter. I got the event_generate() and event property information from the same source.
Be aware that this solution, while it worked for my simple issue, may well require much more care when applied to a more complicated situation.
def fix_keypad(widget):
kmap = {
'<KP_Left>': '<Left>',
'<KP_Right>': '<Right>',
'<KP_Up>': '<Up>',
'<KP_Down>': '<Down>',
'<KP_Home>': '<Home>',
'<KP_End>': '<End>',
'<KP_Next>': '<Next>',
'<KP_Prior>': '<Prior>',
'<KP_Enter>': '<Return>',
}
for i in kmap:
def mfunc(event, key=i):
widget.event_generate(kmap[key], **{'state': event.state})
widget.bind(i, mfunc)

How to simulate button presses in pyside?

What I'm trying to do:
I have a Python(PySide) and Qt/QML UI that today responds to keyboard input (actually it's an IR remote control, but the input events are received as though they were coming from a keyboard).
I want to be able to also respond to mouse events. So where today the user uses arrow keys to navigate to a particular button and presses OK (i.e., Return) to activate the handling for that button, I would like them to just be able to click the mouse on that button and get the same handling behavior.
What I have so far:
I've already got Keys.onReturnPressed: handling in my QML code that does what I need to do when the user presses OK/Return. And I've added MouseArea { ... onClicked: {...} ... } QML code that recognizes when I click on a given control. So I already see in my log when the mouse click events occur.
My question:
How do I tie them together? I want to make the onClicked: behavior just generate some kind of event (a signal, maybe?) that causes the onReturnPressed: handling to be invoked. (I'm not at all averse to passing events through the Python side of things if that's what it takes to make this work.)
(I guess I should mention here that the existing code includes some base classes (is that the right terminology here?) that can define behavior across ALL controls of a certain type (e.g., Buttons) in the system. So while each of the many, many Buttons has its own onReturnPressed: code providing its unique handling, my objective is to have a single onClicked: handler in the base class that makes all Buttons respond to clicks as they do to Return presses today.)
Can anyone point me in the right direction?
BTW: Yes, I'm aware that there's a second problem here, too, of navigation. That is, even once I've turned the mouse click into a press
of the Return key, I still have to solve the problem of associating it
with the right control on the screen.
I sort of didn't want to muddy the waters by asking too many things at once.
I'll get to that one
when I've got this one in hand. (...unless you've got a simple solution already up your sleeve... In that case I'm all ears.)

How to handle button states efficiently in Tkinter

I've done a few searches but I couldn't find anything about this topic. Perhaps because it is common programmer knowledge (I'm not a programmer, I've learned from necessity), or because I'm going about it the wrong way.
I would like ideas/suggestions on how to manage button states for a GUI. For example, if I have a program which allows the user to import and process data, then certain functions should be inaccessible until the data has been imported successfully, or if they want to graph certain data, they need to select which data to graph before hitting the 'graph' or 'export' button. Even in the simple programs I've built these relationships seems to get complicated quickly. It seems simple to say "User shouldn't be able to hit button 'A' until 'B' and 'C' have been completed, then 'A' should be disabled if button 'D' or the 'Cancel' button. But that's a lot to track for one button. Thus far, I've tried two things:
Changing/Checking button states in the callback functions for the button. So in the above example, I would have code in buttons B's and C's callback to check if A should be enabled. And in buttons D's and Cancel's callbacks I would have code to disable button A. This gets complicated quickly and is difficult to maintain as code changes.
Setting boolean variables in every buttons callback (or just checking the states later using cget()) and checking the variables in a polling function to determine which buttons should be enabled or disabled.
I'm just not sure about this. I would like to make code as short and easy to understand as possible (and easy to edit later), but I don't like the idea of polling all the button states every few hundred milliseconds just for button 'management'. You can extend the same idea to check boxes, menu items, etc... but I'd like to here what others have done and why they do it the way they do.
You are only changing button states based on events, right? There is no reason to 'poll' to see if a button state has changed. What you can do is build a function which does all of the calling for you, then call it with something like disable_buttons([okButton, graphButton, printButton]). When an event takes place that modifies the appropriate user interface options (such as importing data), have another function that turns them on: enable_buttons([graphButton]). You could do this with each object's methods, of course, but making a wrapper allows you to be consistent throughout your application.

wxpython: How do I examine dragged data in OnDragOver?

I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?
One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).
There is no way to see dragged data in OnEnter and OnDragOver methods.
The only solution I found is to store the dragged item in some instance variable that is then readable inside these methods.

Categories