Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QLineEdit: how to handle up and down arrows?

Tags:

qt

I have a console input in my Qt based application, it's a QLineEdit, all Ui is designed via QtDesigner. Is it any easy way way to handle up and down arrows in order to implement input history? The 'go to slot' only show returnProcessed signal, no way i can see to handle up and down arrows :(

like image 382
grigoryvp Avatar asked Jan 16 '10 20:01

grigoryvp


3 Answers

I had the same problem, but I find out in other forums that you need to setFocus, e.g.:

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

    this->setFocus();
}

It works for me.

Reference: http://www.qtforum.org/article/28240/how-to-get-arrow-keys.html

like image 130
Sinuhe Tellez Rivera Avatar answered Oct 15 '22 16:10

Sinuhe Tellez Rivera


you can install event filter and watch your line edit event in your window class. Below is an example:

declare event handler method on your window class:

class MainWindow : public QMainWindow {
    Q_OBJECT
...
protected:
    void changeEvent(QEvent *e);
...
};

window constructor

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

event handler implementation:

bool MainWindow::eventFilter(QObject* obj, QEvent *event)
{
    if (obj == ui->lineEdit)
    {
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->key() == Qt::Key_Up)
            {
                 qDebug() << "lineEdit -> Qt::Key_Up";
                 return true;
            }
            else if(keyEvent->key() == Qt::Key_Down)
            {
                qDebug() << "lineEdit -> Qt::Key_Down";
                return true;
            }
        }
        return false;
    }
    return QMainWindow::eventFilter(obj, event);
}

hope this helps, regards

like image 44
serge_gubenko Avatar answered Oct 15 '22 18:10

serge_gubenko


You can subclass QLineEdit and re-implement the virtual keyPressEvent method to handle your special keys.

void MyLineEdit::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Up){
        // move back in history
    }
    else if(event->key() == Qt::Key_Down){
        // move forward in history
    }
    else{
        // default handler for event
        QLineEdit::keyPressEvent(event);
    }
}
like image 26
Kyle Lutz Avatar answered Oct 15 '22 17:10

Kyle Lutz