PDA

View Full Version : keyPressEvent() reimplementation



aurelius
29th October 2008, 21:31
Hi!

I wanted to ask, if i reimplenet keyPressEvent() and I just want to change the operation of a single key event, for example space, can I do it only for this key?

I tried to do it, but if I don't assign tasks for the other keys as well, they don't work. Isn't there a default task for each key for a specific widget, such as TextEdit ?

JimDaniel
29th October 2008, 23:44
I need to see your code, but it sounds like you need to pass the keyPressEvent() up to the base class, so something like this:



MyWidget::keyPressEvent(QKeyEvent * ke)
{
if(ke->key() == Qt::Key_Return)
{
//do something
}

//now pass the keyEvent up to the parent widget,
//here I'm assuming its a QWidget
QWidget::keyPressEvent(ke);
}

aurelius
30th October 2008, 10:02
Yes, I am doing exactly this. There is no point pasting my code here, it's like yours.

What I am trying to do is, to create sth like a console, like a linux console.
So, in my main window, I have a new class that inherits QTextEdit, e.g QConsole.

I reimplement keyPressEvent() function for QConsole as you told me, so I do QConsole::keyPressEvent(){...what you wrote...}. When I add the if statement for Qt::Key_Return, it works perfect. Also, when I add some other key stroke event, it works perfect. Howeve if I don't add them, key strokes don't take their default use.

For example, if I add only Key_Return if statement, the window responds only when I press the return key. All the other don't do anything. When I reimplement keyPressEvent, the other keys don't keep their usual functionality? Is there any way to make them to keep their functionality and change only what I want?

Finally, I don;t see, why I should pass it to some parent widget. The parent widget of the QConsole is just a widget, but ok, I can't see the relation. The thing is tha keyPressEvent suffers.

spirit
30th October 2008, 10:06
did you try to use


QTextEdit::keyPressEvent(ke);

instead of


QWidget::keyPressEvent(ke);

?

aurelius
30th October 2008, 10:19
Ok, guys I found it. I just understood what you meant.

I was actually confused, because when you said that I have to pass it to the base class, for some stupid reason, I thought you meant as base class the widget in which I have as a child my class.

Thank you for your help. :)

JimDaniel
30th October 2008, 16:23
My apologies, I made a mistake referring to the "parent" widget in my comment, when I really meant the base class. A parent is of course something entirely different.