Shortcuts in C++, QT

From Shortcuts Wiki
Jump to: navigation, search

Here is how to create some shortcuts with C++ and Qt (from Qt Development Frameworks). This is based on the release 5 of Qt, but most of it should be working with any release.

Create a QWidget[edit]

Start Qt Designer.

Create a GUI Widgets Application and new window as a QWidget. File > New File or Project > Application > Qt Widgets Application > Choose.

Create a slot to receive the event[edit]

Open the class code corresponding to your windget, for example MyWindow.h and MyWindow.cpp.

Add a slot in the class. That simply means creating a function in the class, no argument, no return value, as a public slot.

 class MyWindow : QWidget
 {
  [...]
 public slot:
   void receiveCtrlK();
 }
 void MyWindow::receiveCtrlK()
 {
    //any code
    ui->lineEdit->setText("Ok, kleared");
 }

Use the QShortcut class[edit]

In the 'cpp' file, include the <QShortcut> header.

Connect the keys to the slot using the QShortcut class, in the constructor of the window.

 #include <QShortcut>
 [...]
 MyWindow::MyWindow(QWidget *parent):
   QWidget(parent)
 {
   [...]
   QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+K"), parent);
   QObject::connect(shortcut, SIGNAL(activated()), this, SLOT(receiveCtrlK()));
 }

More informations[edit]