Reputation: 4700
My program uses a ui-form-file that consists, next to other widgets, of a label called "grip" (its objectname).
As I am running the code, I see the code line grip was not detected
and I am wondering why the mouse click on the label is not recognized. I also have defined a mousePressEvent(QMouseEvent *event)
that works as intended if I click on that label.
bool Note::eventFilter(QObject *target, QEvent *event)
{
if (event->type()==QEvent::MouseButtonPress){
qDebug() << "in Note::eventFilter" << endl;
if (target->objectName()=="grip")
{
lastClicked="grip";
qDebug() << "lastClicked == grip" << endl;
}
else
qDebug() << "grip was not detected" << endl;
}
return false;
}
What may be a reason for target->objectName()=="grip"
being false, if I click on that target and it is called "grip"?
EDIT: That is how my event functions are defined:
void Note::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
qDebug() << "Left mouse button click detected";
...
the main event filter is initialised in the Note's constructor:
Note::Note(std::vector<Note *> *nListIn){
qDebug() << "in Note::Note()" << endl;
ui.setupUi(this);
installEventFilter(this);
setWindowFlags(Qt::FramelessWindowHint);
this->show(); //must be after the Qt::FramelessWindowHint
nList = nListIn;
nList->push_back(this);
qDebug() << "Size of nList (aka noteList)" << nList->size() << endl;
}
EDIT 2: Found some description, might this be the reason?
If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child's underMouse() function inside the widget's mousePressEvent().
Upvotes: 1
Views: 2311
Reputation: 98435
By definition, if you install an event filter only on itself (by calling installEventFilter(this)
, the following holds:
bool Note::eventFilter(QObject *target, QEvent *) {
Q_ASSERT(target == this);
...
}
Obviously, the target won't ever be called grip
, unless you've named the instance of your Note
class that way.
If you want to filter the events on the grip label, then you must install the event filter on that label, not on the Note
widget. The Note
widget will only get events that the children have ignored, and by that time, it doesn't matter that you "filter" them - it's too late.
Your setup code could contain, for example:
ui.grip->installEventFilter(this);
Or, assuming nothing about the structure of the ui
class:
QWidget * grip = findChild<QWidget*>("grip");
if (grip) grip->installEventFilter(this);
Upvotes: 1