PDA

View Full Version : Mouse event handling beyond/outside the widget



keyur259
19th January 2010, 10:43
Hi,

Suppose I have a "Target" class derived from QWidget and I am creating it's object somewhere, suppose in "Source" class, in application. And I want to handle mouse events in this widget even if mouse event is not occured on this widget or occured outside of this widget.

How can I achieve the above things?

Thanks for your help.

Thanks & Regards,
Keyur Shah

caduel
19th January 2010, 10:46
see QWidget::grabMouse(), or QObject::installEventFilter()

keyur259
19th January 2010, 10:48
Thanks for your reply.

I don't have much idea about installEventFilter().

Can you post some code?

wagmare
19th January 2010, 11:14
event filter is an protected function to filter certain event occuring in QObject ex: mouse click, key press, mouse hover, double click
ex:
if i want to filter the key press of key F1

bool DDView:: eventFilter(QObject *ob, QEvent *e)
{
if(e->type() == QEvent::KeyPress){
printf("is it coming inside event..\n");
const QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if(ke->key()==Qt::Key_F1){
printf("F1 buttin clicked..\n");
}
return true;
}
return QWidget::eventFilter(ob, e);
}

and in QWidget constructor add
installEventFilter(this)

keyur259
19th January 2010, 11:45
Thanks for your reply. But I am still missing something. Do you know how to handle "QEvent::NonClientAreaMouseButtonPress"?

caduel
19th January 2010, 12:09
event-filters are used like that

bool DDView:: eventFilter(QObject *ob, QEvent *e)
{
if (ob==someWidget & e->type() == QEvent::KeyPress) {
printf("is it coming inside event..\n");
const QKeyEvent *ke = static_cast<QKeyEvent *>(e);
if(ke->key()==Qt::Key_F1) {
printf("F1 buttin clicked..\n");
}
return true;
}
return QWidget::eventFilter(ob, e);
}

where someWidget would be the widget whose events you want to intercept.
You need to install the event-filter on that widget, first:

someWidget->installEventFilter(this);

Note that QEvent::NonClientAreaMouseButtonPress are mousevents outside of any QWidget (iiuc) and can not be intercepted with an event filter.

Are the mouse events you are interested in inside your window or just somewhere on the desktop? In the latter case you can use grabMouse().

keyur259
19th January 2010, 12:27
I required to close widget if mouse is released outside the widget. There are few buttons inside the widget. I have called grabMouse() in showEvent() of the widget. But however I am able click outside the widget and widget looses it's focus.

I have also tried popup widget, it works fine. But it hasn't titlebar & frame.

keyur259
20th January 2010, 05:14
Do anyone have idea how to achieve it or it's not possible?

Please do reply.

Thanks & Regards,
Keyur Shah