PDA

View Full Version : QMouseevent



jerkymotion
24th March 2011, 07:33
#include "mainwindow.h"
#include "ui_mainwindow.h"


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



}

MainWindow::~MainWindow()
{
delete ui;
}
class Mouse : public QObject
{
Q_OBJECT


protected:
bool eventFilter(QObject *obj, QEvent *event);
};
Mouse *mouse = new Mouse();
bool Mouse::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress) {

return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
QLabel*label=new QLabel();
label->installEventFilter(mouse);


I wanted to install event filter in Qlabel of my ui application ....I have posted the code above but I am having problem with it...I might be declaring the class in wrong section please help me how to install eventfilter in qlabel for mouseevent handling

stampede
24th March 2011, 07:58
Code related to eventFilter looks ok, what are you doing with label after this ? Maybe you just display wrong label in ui. Another thing is that I'm not really sure how your code looks like, is this all one header ? If yes then I'd suggest separate the implementation to .cpp files.
Just tested this code:


// app.h
#include <QObject>

class Mouse : public QObject
{
Q_OBJECT
protected:
bool eventFilter(QObject *obj, QEvent *event);
};




// app.cpp
#include "app.h"
#include <QtGui>

bool Mouse::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress) {
qDebug() << "mouse press";
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget * w = new QWidget();
QVBoxLayout * l = new QVBoxLayout(w);
w->setLayout(l);
QLabel * lbl = new QLabel(w);
lbl->installEventFilter(new Mouse());
l->addWidget(lbl);
w->show();

return a.exec();
}

When clicking on the label I can see "mouse press" text in console window.