Qt: how to apply a two-stage key shortcut to an action

I know how to apply a keyboard shortcut to an action. And in some programs, such as Visual Studio, there are shortcuts that complete the task for more than one step (for example, Ctrl+K , Ctrl+C to comment on the code).

Another example of this in Sublime Text:

I wonder if it can be implemented in Qt.

+5
source share
3 answers

Try the following:

 action->setShortcut("Ctrl+K,Ctrl+C"); 

QKeySequence can be implicitly created from QString . Due to the documentation :

You can enter up to four key codes, separated by commas, for example. "Alt + X, Ctrl + S, Q".

MOC generates almost the same code when creating a shortcut for QAction through Qt Designer. But this is a little different:

 action->setShortcut(QApplication::translate("MainWindow", "Ctrl+K, Ctrl+C", 0)); 

but it’s actually the same.

+1
source

You can create it using the multiple argument constructor for QKeySequence .

like this:

 auto ac = new QAction(this); ac->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K, Qt::CTRL + Qt::Key_C)); 
+1
source

You can use eventFilter to get mouse and keyboard events.

I use boolean to get the first and second keys, Ctrl + K and C.

I made you a sample code that works.

.cpp file:

 #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); firstKey = false; secondKey = false; this->installEventFilter(this); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::eventFilter(QObject *object, QEvent *event) { if (object == this &&event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if ((keyEvent->key() == Qt::Key_Control)) { firstKey = true; return true; } else if ((keyEvent->key() == Qt::Key_K)) { secondKey = true; return true; } else if ((keyEvent->key() == Qt::Key_C)) { if(firstKey && secondKey) { firstKey = false; secondKey = false; QMessageBox::information(this, "", "Ctrl + k + c"); } return true; } else return false; } else return false; } void MainWindow::keyReleaseEvent(QKeyEvent *e) { if (e->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e); if ((keyEvent->key() == Qt::Key_Control)) { firstKey = false; } } } 

.h file:

 #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QDebug> #include <QMessageBox> #include <QKeyEvent> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); bool firstKey; bool secondKey; bool eventFilter(QObject *object, QEvent *event); void keyReleaseEvent(QKeyEvent *e); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H 
0
source

Source: https://habr.com/ru/post/1270461/


All Articles