Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

LineEdit only allow specific keyPressEvent



  • I am using win10 and qt5.

    I would like to disable everything if I press a button on the keyboard except the moving the cursor. When I pressed right or left arrow I would like to move the cursor.

    LineEdit.h

    #pragma once
    
    #include <QLineEdit>
    #include <QKeyEvent>
    #include <QDebug>
    
    class LineEdit : public QLineEdit {
    
        Q_OBJECT
    
    public:
    
        LineEdit(QWidget* parent = nullptr)
            : QLineEdit(parent) {}
    
        virtual void keyPressEvent(QKeyEvent* event) override {
    
            if(event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
                event->accept();
                qDebug() << "accept";
            }
            else {
                event->ignore();
                qDebug() << "ignore";
            }
    
        }
    
    };
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    #include "LineEdit.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow) {
        ui->setupUi(this);
    
        QWidget* window = new QWidget;
    
        LineEdit* line = new LineEdit(window);
        line->setText("abcdefgh");
    
        setCentralWidget(window);
    }
    
    MainWindow::~MainWindow() {
        delete ui;
    }
    

    I get the appropiate qDebug output, so that cannot be the problem.



  • @kocka Change to:

    if(event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
            QLineEdit::keyPressEvent(event);
            return;
    }
    


  • @kocka Change to:

    if(event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
            QLineEdit::keyPressEvent(event);
            return;
    }
    

Log in to reply