PDA

View Full Version : problem with keypressevent inside textedit



serula
23rd April 2011, 14:05
hi,

im a beginner in programming, im creating a school assignment, such that any keyboard input inside a textedit will be display what type of key entered in the label below.

void MainWindow::keyPressEvent(QKeyEvent *event){
if(event->key() == Qt::Key_0 )
{ui->label->setText("Numbers 0 press");}
.........
.........
else
ui->label->setText("Other keys press");


*attached is the source code.

but the problem is when any key press inside the textedit will not produce any outcome, but if the focus is outside the textedit box (for example by pressing the dummy button) the function will execute.

i search existing thread but doesnt find anything beneficial..
i am highly grateful by any help from u guys


6282

high_flyer
27th April 2011, 08:26
but the problem is when any key press inside the textedit will not produce any outcome,
That is because you have overridden the keyPressEvent of your MainWindow and not of the QTextEdit.
You have two options:
1. Use an event filter - this way you don't need to subclass QTextEdit.
Look in the docs for the QObejct::installEventFilter() they have a "key eater" example there.
2. Subclass QTextEdit and re implement its keyPressEvent().

serula
27th April 2011, 17:06
Hi, high_flyer, thanks for the reply, im interested if possible in using option 2. (Subclass QTextEdit and re implement its keyPressEvent()). i understand the use of subclassing from my programming class, but applying to Qt is a different whole different lvl to me,
i search the forum the nearest explanation of subclassing is

http://www.qtcentre.org/threads/40903-keyPressEvent-of-QPlainTextEdit-on-a-QDialog


the author said theres not much goes into detail on how exactly to subclass the object, (i tried but mostly come with error on ambiguity and no matching function for call to) is there any example on how to apply this , thanks again

high_flyer
28th April 2011, 08:33
I am sorry, but sub classing is C++ basics, and its off topic for this forum.
You will be more helped on C++ tutorial sites.
However feel free to ask any Qt related questions you have.
If you are not comfortable with sub classing, why do you go for option 2 and not option 1?

serula
28th April 2011, 13:03
Thanks again for the advice ..