Skip to main content

Command Palette

Search for a command to run...

Coding notes

Published
•1 min read•View as Markdown

Catch the press event of the keystroke

  1. Overwrite event filter.

     //.h file
     bool eventFilter(QObject* obj, QEvent* event) override;
    
     //.cpp file
     bool MainWindow::eventFilter(QObject* obj, QEvent* event)
     {
         if (event->type() == QEvent::KeyPress)
         {
             //force conversion
             QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
    
             //eg. press T + Ctrl keys at the same time (pay attention to the type of different keys: key or modifiers)
             if (keyEvent->key() == Qt::Key_T && keyEvent->modifiers() == Qt::ControlModifier)
             {
                 //special handle...
             }
             else
             {
                 return QObject::eventFilter(obj, event);
             }
    
             return true;
         }
         else
             return QObject::eventFilter(obj, event);
     }
    
  2. Install the event filter in the class constructor.

  • Sometimes must install for qApp(not sure why)
qApp->installEventFilter(this);

Enable/disable the window to stay on top

The implementation code must be written in the constructor of the class, otherwise, it will have no effect.

Code as below:

//Enable
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
//Disable
setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint);

show();  //sometimes need this code to be added at the end (not sure why)

NEXT...