views:

278

answers:

2

Hey everyone,

I have a problem with Qt 4.6.0 and shortcut for QPushButtons :

I want to display a special text in a QTextEdit when the user clicks a button, but only when the button is pressed, as soon as it's released, i want another text to come up.

Everything works fine but now I want to add a shortCut (let's say F1) to perform the exact same operation, when I push F1 it displays something special in a QTextEdit 'til I release the key. How do I manage to do this ?

I added the shortCut on my button, but when I press F1, it's blinking, it's like as long as I press F1, lots of signals are being emitted... I want my QTextEdit to change when I press F1 and then change back when I release the key...

I hope my question is clear !

Thanks a lot in advance for your advices !

+1  A: 

I think the most simple solution to this problem is to use installEventFilter() on the parent object (the window), and filter out the QEvent::MouseButtonPress and QEvent::MouseButtonRelease events.

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
 if (obj == textEdit) {
     if (event->type() == QEvent::KeyPress) {
         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
         qDebug() << "Ate key press" << keyEvent->key();
         return true;
     } else {
         return false;
     }
 } else {
     // pass the event on to the parent class
     return QMainWindow::eventFilter(obj, event);
 }
}
BastiBense
Hey, thanks for the answer ! You're right, I finally chose this solution, but something makes me think it's not a proper way to do... The thing is, the QPushButton is all setup up to react to other event in my application, and I have to "copy" those reaction for my shortcut... I think it's breaking the DRY principle and I don't really like it...For example, at some point, my QPushButton is disabled, I don't want to do any work to disable the shortcut as well, since the shortcut should be a property of the QPushbutton, and therefore, should be off when the QPushButton is off.
Andy M
You are right, it doesn't *feel* right, but I consider this custom behavior to be exotic to the nature of QPushButton (users expect it to do something when it is clicked once, not any reaction when they press the mouse key down without releasing it). I guess as long as you don't have to do this for a few hundred buttons, and it's not all over your application, this is a clean, and easily readable way of getting your button to behave as you wish.
BastiBense
Yeah I guess, it's correct that it's not a basic behavior of QPushButton... Anyway, I'll go with that solution... Thanks for your help !
Andy M
+1  A: 

A push button emits the signal clicked() when it is activated by the mouse, the Spacebar or by a keyboard shortcut. You'll have to handle key press and key release to do what you want.

Nikola Smiljanić
Basically that's what I suggested in my answer earlier (see below).
BastiBense