How to intercept / modify excape key functionality in Qt - qt

I am trying to fix a bug in a Qt app which I did not write. The window changes the background color of the entire window to red and puts up some buttons, dialog boxes, etc. When the escape key is pushed, the boxes and buttons go away, leaving an empty red screen. The Cancel button does the right thing in returning to the previous window. I think I need to somehow be notified of when the escape key is pushed, and then call the same function as the cancel pushbutton does. Hopefully, I can limit the scope of this special action to when the problem window is up. I am an experienced programmer but a complete Qt newbie. This app is purely C++. To my knowledge, it does not appear to use any QML. I am still searching through the Qt online documentation, but any suggestions / examples are appreciated.

This depends a lot on your specific Qt version and setup of your application. That said, I'll take a shot at helping. In the class where you're trying to intercept the escape key press, assuming it's inheriting QObject, simply override the virtual function eventFilter. Inside your overridden instance of eventFilter, check that the QEvent type is a QEvent::KeyPress, and then check whether the key of that KeyPress is the escape key, and handle as needed.
Be sure that you pass the event out of your function, else you'll see your overridden function eat all events. If you explicitly want the event to be "eaten", simply do not return it from your function. For specifics and examples, check out documentation of QObject::eventFilter().

Related

Tkinter Leave event firing only on program startup?

I'm trying to place a small label hinting the user the keyboard shortcut bound to it, which works fine.
The problem arises when I'm leaving the button. The label disappears, but not quite. If I try to click the button in the area the label "used" to be, it won't fire, indicating that's it's somehow still there. So I thought maybe buttons have a Leave event already built in that raises them to the top level. I decided to try and override that, and basically tell the button go (or better yet, just stay) below the key-hint label hit_button.bind("<Leave>", hit_button.lower(hit_button_keyhint), to no avail. What am I doing wrong?
fg=hit_button['fg'])
hit_button_keyhint.place(relx=0.5, rely=0.85, anchor='center')
hit_button.bind("<Leave>", hit_button.lower(hit_button_keyhint))
You need to pass a function to the binding, Here you execute a function. (hit_button.lower(hit_button_keyhint))
To do so, you should use a lambda.
You can get some clarifications here:
Tkinter binding a function with arguments to a widget
But this should work:
hit_button.bind("<Leave>",lambda event, k=hit_button_keyhint:hit_button.lower(k)

Qt Editable QGraphicsTextItem validating text and emitting signal on change

I am really stuck up with a task relating to Qt GraphicsView. Any help or suggestions will be highly appreciated.
In my QGraphicsView application, I have a few editable QGraphicsTextItems that I have added to the scene. I need the following functionality:
Setting validator for float so that the user does not by mistake enter a character or new line in that text item.
Emitting a signal once the text is changed by the user.
Can anyone please suggest how I can implement this in my application? I have tried real hard but I am not able to find anything suitable. If there is any alternative or workaround, I'll be grateful to know.
Thanks!
QGraphicsTextItem does not support this ability, as I'm sure you have discovered. So you have a few options:
Reimplement focusOutEvent(QFocusEvent* event) and/or keyReleaseEvent(QKeyEvent* event) to detect when you validator needs to run. A QValidator can be created as a member of your text class, and queried either when focus is lost and/or a key is pressed (the enter key to signify completion, or on every letter). Then just create a custom signal for you when deem the editing to have finished or changed.
Use a GraphicsProxyWidget to hold a 'real' QLineEdit for text entry, just set it up with a validator as you would if placing in a traditional GUI form. You will need to 'forward' the editingFinished() or textEdited(const QString& text) signal from the QLineEdit to your QGraphicsTextItem, so you don't have to provide external access to the widget.
You could also use the internal QTextDocument of the QGraphicsTextItem, this is what actually holds and formats the text (access it with document()). However it doesn't support having a QValidator installed, so you would have to create a signal-slot loop whereby when the text is changed (signalled by contentsChanged()) it's received by the QGraphicsTextItem, validated, then either updated/cleared if it fails validation (which will update the QTextDocument, and trigger this process again) or ignored if it passes.
Neither is difficult to implement; the first requires more code but will give you more control over the visual appearance of the text box.

Qt : keyboard focus

I am writing a program in Qt that looks like this:
The main window is my class Window : QWidget, it has a QGridLayout containing four other widgets (Input_Menu : QWidget and Output_Menu : QWidget, and then two Canvas : QWidget)
I would like to trigger certain events when the user strikes a key. The problem is, the Window sometimes loses focus (it goes, say to Input_Menu, or maybe a button in Input_Menu...)
I have tried the following solutions, but they seem unsatisfactory (and dirty):
Give Window the focus whenever it loses it.
Tell each widget who could have the focus to trigger Window's KeyPressEvent function (or a clone of it) whenever it receives a keyboard event.
Ideally, I would like that if a widget receives an event (say a keyboard event) and doesn't know what to do with it, it should automatically call its parent's event handler. I would have hoped this to be a default feature of Qt but it doesn't look like it. On the other hand I am really confused about the whole focus thing, I don't really get what's going on. Can someone explain this to me: I have included a std::cout << "key pressed" << std::endl; in my Window::KeyPressEvent function. When I first run my program, it seems the focus is on the top QComboBox in Input_Menu: if I hit the Up/Down keys, I navigate in that box and no "key pressed" is showed in my console. If I hit most letters, nothing happens. But if I hit Left/Right keys, I do get a "key pressed" in my console!?
Thanks a lot in advance for your insights.
You can install an event filter on QApplication to filter the relevant QEvent::KeyPress events globally. From the Qt documentation:
It is also possible to filter all events for the entire application,
by installing an event filter on the QApplication or QCoreApplication
object. Such global event filters are called before the
object-specific filters. This is very powerful, but it also slows down
event delivery of every single event in the entire application; the
other techniques discussed should generally be used instead.
Besides the performance considerations, remember to check if your window currently has the focus before you filter the key event, or you might break popup dialogs or input into other windows.
Actually, I found that for keys that are modifiers (such as Shift, Control), Qt supports finding out whether they are pressed.
Eg : if(QApplication::keyboardModifiers() == Qt::ShiftModifier) ...
This is good enough.

Qt: How to initialize dialog widgets?

I would like to know what the established procedure is for initializing the controls within a Qt custom dialog box. In the code I am writing, the dialog would present a QListView containing directories from an object passed (by reference) to the dialog class during construction. When the dialog is displayed, I obviously want the list to display the directories currently configured in the object.
Where should this be done though? Perhaps in the overridden showEvent() method?
Background: I used to do a lot of MFC programming back in the day, and would have done this sort of stuff in the OnCreate method, or some such, once the window object had been created.
Thankfully Qt doesn't require you to do any hooking to find the moment to create things (unless you want to). If you look over the Qt examples for dialogs, most do all the constructing in the constructor:
http://doc.qt.io/archives/qt-4.7/examples-dialogs.html
The tab dialog example--for instance--doesn't do "on-demand" initializing of tabs. Although you could wire something up via the currentChanged signal:
http://doc.qt.io/archives/qt-4.7/qtabwidget.html#currentChanged
Wizard-style dialogs have initializePage and cleanupPage methods:
http://doc.qt.io/archives/qt-4.7/qwizardpage.html#initializePage
http://doc.qt.io/archives/qt-4.7/qwizardpage.html#cleanupPage
But by and large, you can just use the constructor. I guess the main exception would be if find yourself allocating the dialog at a much earlier time from when you actually display it (via exec), and you don't want to bear the performance burden for some part of that until it's actually shown. Such cases should be rare and probably the easiest thing to do is just add your own function that you call (like finalizeCreationBeforeExec).

QWidget signal sent when menu action selected - how do I prevent this?

In more than one of my Qt applications I've noticed that, whenever the menu bar is clicked, the last signal to have been sent from a widget within the GUI is re-sent before the menu action is invoked. Most of the time this doesn't matter; but on some occasions it matters very much.
In a few cases where the widget's signal is connected to one of its own slots, it's straightforward to begin the slot with a
if (hasFocus())
{
// ...
}
...block so that such spurious signals, not generated by the user actually clicking on the widget, can be ignored.
However, I've recently identified that this behaviour is responsible for several related bugs where the spurious signals are passed on through several layers of the program before being acted upon, so simply checking whether a particular widget has focus is not trivial to implement.
My question, therefore, is:
why on earth does clicking on a menu item cause a signal to be emitted from a widget elsewhere on the screen? I can't find this behaviour documented anywhere?
how do I stop it?
Many thanks,
Stephen.
As you deduced yourself, the QLineEdit::editingFinished signal can be emitted twice if the user press enter and the QLineEdit loses the focus later. An old bug was created but behaviour has not been changed : https://bugreports.qt.io/browse/QTBUG-40.
Your solution is fine : overload QLineEdit and check if the value has changed before triggering the signal. You can use the flag QLineEdit::isModified for the check : it has a default value of false and is changed to true whenever the user changes the line edit's contents. It has to be manually reset to false when you emit the signal.
You can also do that check in the receiver object, just checking if the value has a meaning (is different from the last recorded value for example) and process it or not.
Therefore the polluting signals would not be a problem. It is in my opinion the cleanest solution, then you have a robust model. Because the user could also hit enter a few times with the same text value and you have to handle this anyway.
You can also use QLineEdit::returnPressed but this requires the user to always press enter to validate a value. Not always intuitive but forces the user to explicitly validate the inputs.

Resources