PDA

View Full Version : KeyEvent Handling



parulkalra14
21st January 2014, 07:09
I want whenever i press tab space cursor will move 4 position forward. I tried this code but its not working. Can anybody tell me what is wrong with the code? Why this code is not working?

void MainWindow::keyPress(QKeyEvent *eve)
{
if (eve->key()==Qt::Key_Tab)
{
ui->plainTextEdit->insertPlainText(" ");
}
}

StrikeByte
21st January 2014, 09:56
What type of class is your mainwindow if it is QMainWindow you can use void keyPressEvent(QKeyEvent *); (I dont know if it also triggers on child items)

else you can install an eventfilter

installEventFilter(this);

add this function to the main window
bool MainWindow::eventFilter(QObject *obj, QEvent *event)

in the filter you can check for a specific object and event
if the event is the one you need you can entirely filter it by returning true (the event will be seen as handled) else return false (event will go to child objects)

parulkalra14
21st January 2014, 10:42
But i want cursor will move 4 spaces ahead instead of 8 spaces whenever i press tab space. How it will be done?

StrikeByte
21st January 2014, 11:40
use the eventfilter and return true if you receive the tab key, if you dont filter it you will do 4 spaces and then when the input box receives the tab it will add another tab

edit:
made some code


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

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) //event is installed on the lineedit so not checking object
{
QKeyEvent *key = dynamic_cast<QKeyEvent*>(event);
if(key && key->key() == Qt::Key_Tab)
{
ui->lineEdit->insert("!!!!");
return true;
}
}
return false;
}

parulkalra14
21st January 2014, 12:28
@StrikeByte: thanku so much sir its working fine now......:)

anda_skoa
21st January 2014, 13:17
Or derive from the text edit and implement it directly in the class that gets the events.

Cheers,
_