Keyboard arrows in QT

2

When we want to use the keyboard arrows in C ++, we use the Ncurses or conio.h libraries, depending on the operating system.

But is there a way to do this using the QT libraries?

    
asked by anonymous 08.05.2018 / 22:09

1 answer

3

Yes, using QKeySequence with QAction for example if you need to fire a specific SLOT , example in MainWindow.h would have the following slot:

private slots:
    void meuEvento();

And in MainWindow.cpp would have this:

#include <QKeySequence>
#include <QAction>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QKeySequence seq = QKeySequence(tr("Ctrl+S"));

    QAction *act = new QAction(this);

    QObject::connect(act, SIGNAL(triggered()), this, SLOT(meuEvento()));

    this->addAction(act);

    act->setShortcut(seq);
}

void MainWindow::meuEvento()
{
    qDebug() << "TESTE";
}

In the example the third parameter is this of QObject::connect , which refers to the class where the meuEvento slot is, but of course it can point to slots of other objects.

You can use a string with + as the QKeySequence(tr("Ctrl+S")) separator or use the constants , example:

QKeySequence(Qt::CTRL + Qt::Key_S);

More consistent: link

I've also developed a small library for more personal use, but I share that aims to "somewhat lessen the writing of code" :

Download at link , then extract the part that is important to you, in the case the folder that will be used is:

/application/keysequence/

There are 3 files in it:

  • keysequence.h
  • keysequence.cpp
  • keysequence.pri

Put the keysequence folder inside your project and add it to your .pro

include($$PWD/keysequence/keysequence.pri)

So if you want to add an event to Mainwindow , do this:

#include "keysequence.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    KeySequence::widget(this, "Ctrl+W", this, SLOT(meuEvento()));
}

If it's a specific widget do this:

ui->setupUi(this);

KeySequence::widget(ui->textField, "Ctrl+W", this, SLOT(meuEvento()));
  

In the examples Ctrl + W running the event, you can customize this or use QKeySequence::StandardKey

    
09.05.2018 / 00:45