How to make Esc key to minimize a dialog? By default it closes. Should I process KeyEvent or there is a better way?
I think you may use this:
void MyDialog::keyPressEvent(QKeyEvent *e) {
if(e->key() != Qt::Key_Escape)
QDialog::keyPressEvent(e);
else {/* minimize */}
}
Also have a look at Events and Event Filters docs.
Escape calls reject(). I override this function (in my case not to minimize the dialog but to prompt to save)
void MyDialog::reject() {if(cleanupIsOK()) done(0);}
Al_
Renaming the reject is correct. But be careful because if you want to close the dialog in other way you cannot call close.
MyDialog::reject(){
if(some_closing_condition)
{
QDialog::reject() //calls the default close.
}
else
{
//skip reject operation
}
}
I think that to do this, you would basically have to avoid inheriting from QDialog. The documentation for QDialog says:
Escape Key
If the user presses the Esc key in a
dialog, QDialog::reject() will be
called. This will cause the window to
close: The close event cannot be
ignored.
Interestingly Qt docs state ESC calls reject()
Escape Key
If the user presses the Esc key in a dialog, QDialog::reject() will be
called. This will cause the window to close: The close event cannot be
ignored
yet QDialog::reject() documentation says hides. i.e closeEvent() is not called, which I have confirmed to be the case.
void QDialog::reject()
Hides the modal dialog and sets the result code to Rejected
Related
So, I have an application where if a particular button is kept pressed it plays an audio device, when the button is released it stops the audio device. I use keyPressEvent and KeyReleaseEvent to implement this which is similar to the code below:
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 pressed"<<endl;
}
else
{
QWidget::keyPressEvent(event);
}
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if(event->isAutoRepeat())
{
event->ignore();
}
else
{
if(event->key() == Qt::Key_0)
{
qDebug()<<"key_0 released"<<endl;
}
else
{
QWidget::keyReleaseEvent(event);
}
}
}
But apparently isAutoRepeat function isn't working as I can see continuous print out of key_0 pressed and key_0 released despite the fact I haven't released the 0 key after I have pressed it. Is my code wrong or something else is wrong?
Thanks.
EDIT
I think this is happening because the MainWindow loses the keyboard focus. How can I actually find out which widget has the focus? I'm actually using some widgets when Qt::Key_0 pressed, but I thought I set all those possible widgets to Qt::NoFocus, I guess it's not working.
I'm trying to know which widget has the focus by doing the following:
QWidget * wigdet = QApplication::activeWindow();
qDebug()<<wigdet->accessibleName()<<endl;
but it always prints an empty string. How can I make it print the name of the widget which has the keyboard focus?
So as I also stumbled over this issue (and grabKeyboard didn't really help), I begun digging in qtbase. It is connected to X11 via xcb, and by default, in case of repeated keys, X11 sends for each repeated key a release-event immediately followed by a key-press-event. So holding down a key results in a sequence of XCB_BUTTON_RELEASE/XCB_BUTTON_PRESS-events beeing sent to the client (try it out with xev or the source at the end of this page).
Then, qt (qtbase/src/plugins/platforms/xcb/qxcbkeyboard.cpp) tries to figure out from these events whether its an autorepeat case: when a release is received, it uses a lookahead feature to figure if its followed by a press (with timestamps close enough), and if so it assumes autorepeat.
This does not always work, at least not on all platforms. For my case (old and outworn slow laptop (Intel® Celeron(R) CPU N2830 # 2.16GHz × 2) running ubuntu 16.04), it helped to just put a usleep (500) before that check, allowing the press event following the release event to arrive... it's around line 1525 of qxcbkeyboard.cpp:
// look ahead for auto-repeat
KeyChecker checker(source->xcb_window(), code, time, state);
usleep(500); // Added, 100 is to small, 200 is ok (for me)
xcb_generic_event_t *event = connection()->checkEvent(checker);
if (event) {
...
Filed this as QTBUG-57335.
Nb: The behaviour of X can be changed by using
Display *dpy=...;
Bool result;
XkbSetDetectableAutoRepeat (dpy, true, &result);
Then it wont send this release-press-sequences in case of a hold down key, but using it would require more changes to the autorepeat-detection-logic.
Anyway solved it.
The problem was that I have a widget which is a subclass of QGLWidget which I use to show some augmented reality images from Kinect. This widget takes over the keyboard focus whenever a keyboard button is pressed.
To solve this problem, I needed to call grabKeyboard function from the MainWindow class (MainWindow is a subclass of QMainWindow), so this->grabKeyboard() is the line I needed to add when key_0 button is pressed so that MainWindow doesn't lose the keyboard focus, and then when the key is released I needed to add the line this->releaseKeyboard() to resume normal behaviour, that is, other widgets can have the keyboard focus.
I know one method of preventing an MFC dialog from closing when the Enter or Esc keys are pressed, but I'd like to know more details of the process and all the common alternative methods for doing so.
Thanks in advance for any help.
When the user presses Enter key in a dialog two things can happen:
The dialog has a default control (see CDialog::SetDefID()). Then a WM_COMMAND with the ID of this control is sent to the dialog.
The dialog does not have a default control. Then WM_COMMAND with ID = IDOK is sent to the dialog.
With the first option, it may happen that the default control has a ID equal to IDOK. Then the results will be the same that in the second option.
By default, class CDialog has a handler for the WM_COMMAND(IDOK) that is to call to CDialog::OnOk(), that is a virtual function, and by default it calls EndDialog(IDOK) that closes the dialog.
So, if you want to avoid the dialog being closed, do one of the following.
Set the default control to other than IDOK.
Set a handler to the WM_COMMAND(IDOK) that does not call EndDialog().
Override CDialog::OnOk() and do not call the base implementation.
About IDCANCEL, it is similar but there is not equivalent SetDefID() and the ESC key is hardcoded. So to avoid the dialog being closed:
Set a handler to the WM_COMMAND(IDCANCEL) that does not call EndDialog().
Override CDialog::OnCancel() and do not call the base implementation.
There is an alternative to the previous answer, which is useful if you wish to still have an OK / Close button. If you override the PreTranslateMessage function, you can catch the use of VK_ESCAPE / VK_RETURN like so:
BOOL MyCtrl::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_KEYDOWN )
{
if(pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)
{
return TRUE; // Do not process further
}
}
return CWnd::PreTranslateMessage(pMsg);
}
The answer of #the-forest-and-the-trees is quite good. Except one situation which was addressed by #oneworld. You need to filter messages which are not for dialog window:
BOOL CDialogDemoDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->hwnd == this->m_hWnd && pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam == VK_RETURN || pMsg->wParam == VK_ESCAPE)
{
return TRUE; // Do not process further
}
}
return CWnd::PreTranslateMessage(pMsg);
}
Remember to add virtual in the header file.
When dealing with Dialog style MFC applications, the framework automatically hard codes a few items that must be overridden to prevent the application from quitting when the Esc or Enter keys are pressed. But there is a very simple way that doesn't require anything special such as implementing PreTranslateMessage() which is very much not recommend.
There are three functions that need to be in place:
The OnCancel() function to override the base class version and not to call it. This prevents the Esc key from closing the app.
The OnOK() function to override the base class version and not to call the base class. This prevents the Enter key from closing the app.
Because you've now prevented the dialog window from being closed you must now implement the OnClose() event handler. This function handler will handle when the Windows "X" button or the system command Close Alt+F4 are clicked. Now in order to close the application, you then call the base class version of one of the other functions OnOK(), OnCancel() if desired, to actually close the app. At this point you now have full control of how the app is closed.
Step 1
In the header, add the three function prototypes.
You can use the Class Wizard if you like to add the WM_CLOSE event handler but it's super simple to just type it in.
// DefaultDialogAppDlg.h
//
class CDefaultDialogAppDlg : public CDialogEx
{
// ... other code
protected:
virtual void OnCancel(){} // inline empty function
virtual void OnOK(){} // inline empty function
public:
afx_msg void OnClose(); // message handler for WM_CLOSE
// ...other code
};
Step 2
In the .cpp file, add the ON_WM_CLOSE() entry to the message map and the definitions for the three functions. Since OnCancel() and OnOK() are generally going to be empty, you could just inline them in the header if you want (see what I did in Step 1?).
The .cpp file will have something like this:
// DefaultDialogAppDlg.cpp
// ... other code
BEGIN_MESSAGE_MAP(CDefaultDialogAppDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CLOSE() // WM_CLOSE messages are handled here.
END_MESSAGE_MAP()
// ... other code
void CDefaultDialogAppDlg::OnClose()
{
// TODO: Add exit handling code here
// NOTE: to actually allow the program to end, call the base class
// version of either the OnOK() or OnCancel() function.
//CDialogEx::OnOK(); // returns 1 to theApp object
CDialogEx::OnCancel(); // returns 2 to theApp object
}
I simply override the OnOk event and instead of passing the message to the parent dialog, do nothing.
So it's basically simple as doing so:
void OnOk() override { /*CDialog::OnOK();*/ }
This should prevent the dialog from closing when pressing the return/enter key.
Make sure you don't #define CUSTOM_ID 2 because 2 is already defined for escape and I think 1 is defined for enter? Correct me if i'm wrong.
How can I suppress to close the form when hitting the OK button? I have the following code:
void __fastcall TfrmTillegg_velg::btnOkClick(TObject *Sender)
{
if (exp1)
ShowMessage("Not allowed"); // Don't close form
else if (exp2)
ShowMessage("Not allowed"); // Don't close form
else
{
// Do something here
Close();
}
}
The project is written in Borland c++builder.
If you mean keeping the dialog created by ShowMessage open. then as far as I am aware, you cannot do this. The dialog displayed by ShowMessage will close whenever you click any of its buttons. If you want a popup dialog that will not close in this way, you will need to create a custom form yourself and control its behaviour according to your needs.
Just in case your question is referring to your main form closing, then you do have an explicit call to Close() within your button click event handler above that will cause your form to close whenever both of your exp1 and exp2 conditions are false.
else {
// Do something here
Close(); // THIS WILL CLOSE YOUR MAIN FORM.
}
How do I implement Close (or exit) function when the ESC key is pressed in a form application in C++ builder?
Also, note that the form will have a number of components; it can't be only an empty form.
I tried to use this code but it doesn't work every time I press ESC.
void __fastcall TForm1::FormKeyPress(TObject *Sender, System::WideChar &Key) {
if (Key == VK_ESCAPE) {
this->Close();
}}
The code above doesn't work because focus is not always on the form and, if you have more components like EditBox, you have to disable VK_ESCAPE on every event and reference the desired function (which is, of course, a weak solution).
Using the TForm::KeyPreview property and TForm::OnKeyPress event is the best approach, but an alternativve would be to put a hidden TButton on the form and set its Cancel property to true, then you can call Close() in its OnClick event.
Set the KeyPreview property of the Form to true. This way, keyboard events occur on the form, before the active control.
I have a dialog which I need to show both inside a CPropertySheet and as a standalone dialog. I've chosen not to have 2 separate classes to avoid code redundancy (I make changes a lot in those dialogs, and having to sync 2 classes constantly would be hell), instead when I want to show it as a standalone dialog, I just call CPropertyPage::DoModal. This causes some problems, but I've fixed most of them.
However, some still remain, namely enter and esc don't work. Also pressing tab doesn't change the focus. This makes me think that CPropertyPage eats up all keyboard input, or maybe it tries to pass them to its parent.
Any ideas how I can override that behaviour in the standalone mode?
I believe this would work for you. I don't have a dialog that I can test this with so I am doing this all from memory but I believe you could add a bool that you set when you call DoModal or expose it as a property that you set before the call to DoModal to indicate it is running as a stand alone dialog, then override PreTranslateMessage like this:
CMyPropertyPage::PreTranslateMessage(MSG* pMsg)
{
if (m_runningAsStandalone && pMsg->message == WM_KEYDOWN)
{
UINT key = pMsg->wParam;
switch(pMsg->wParam)
{
case VK_RETURN:
OnOK();
return TRUE;
case VK_ESCAPE:
OnClose();
return TRUE;
}
}
return CPropertyPage::PreTranslateMessage(pMsg);
}
You may also find this link helpful http://support.microsoft.com/kb/125645