How to Program custom Keyboard Shortcuts

后端 未结 4 1067
北荒
北荒 2020-12-24 13:19

I have a Qt application on Linux.

I\'d like to program custom keyboard shortcuts such as CTRL-Q which will then call a subroutine which quits

相关标签:
4条回答
  • 2020-12-24 13:45

    Since CTRL-Q may have a menu item or toolbar entry, too, I think you're looking for QAction.

    See this: http://doc.qt.digia.com/4.6/qaction.html#shortcut-prop

    LE:

    Example of QAction at work:

    QAction *foo = new QAction(this);
    foo->setShortcut(Qt::Key_Q | Qt::CTRL);
    
    connect(foo, SIGNAL(triggered()), this, SLOT(close()));
    this->addAction(foo);
    

    Just create a new Qt GUI project (I used QtCreator) and add that code to the main window's constructor and it should work as expected.

    Please note that there is no need of freeing the memory since the Qt framework will take care of that when the app closes.

    0 讨论(0)
  • 2020-12-24 13:51

    For the modern Qt (5.9 as of now):

    void MainWindow::bootStrap()
    {
        // create shortcut
        QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this);
    
        // connect its 'activated' signal to your function 'foo'
        QObject::connect(shortcut,    &QShortcut::activated,
                         this,        &MainWindow::foo);
    }
    
    // somewhere in the code, define the function 'foo'
    void MainWindow::foo()
    {
        qDebug() << "Ctrl+Q pressed.";
    }
    

    Don't forget to #include <QShortcut>.

    Further info: http://doc.qt.io/qt-5/qshortcut.html

    0 讨论(0)
  • 2020-12-24 14:04

    Try this:

    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
    

    You can create it in the contructor of your form. This allows to avoid polluting your class with a pointer to access the shortcut. You may still want to add a pointer to the shortcut if you want to access it later on. The shortcut will be deleted when the application exits, since it is parented to it. It automatically does the connection, you don't have to do it manually.

    Also note that there is no default Ctrl+Q sequence on Windows, but there is one on Linux and MacOS.

    0 讨论(0)
  • 2020-12-24 14:04

    this is a sample to create file menu and exit action and connection between signal and slot.

    QMenu *fileMenu = new QMenu(trUtf8("&File"));
    QAction *actionExit = new QAction(tr("E&xit"));    
    //set "ctrl+q shortcut for exit action
    actionExit->setShortcut(tr("CTRL+Q"));
    //connect triggered signal of actionExit to close slot
    connect(actionExit, SIGNAL(triggered()), this, SLOT(close()));
    //add actionExit into file menu
    fileMenu->addAction(actionExit);
    
    0 讨论(0)
提交回复
热议问题