简体   繁体   中英

eventFilter(QObject *obj, QEvent *e) does not detect right object

I expect my program to print "mouse on label name" when my mouse is located on the labelname (a QLabel ), and to print"mouse not on label name" when my mouse is not located on the labelname .

Even though I put my mouse on labelname , my program prints "mouse not on label name".

How can I know when my mouse is not on the labelname ?

bool Dialog::eventFilter(QObject *obj, QEvent *e)
{
    if(qobject_cast<QLabel*>(obj) == ui->labelname) {
    cout << “mouse on label name” << endl;
    }else if(qobject_cast<QLabel*>(obj) != ui->labelname) { 
    cout << “mouse not on label name” << endl;
    }
    return false;
}

Be sure you are installing the event filter correctly. Also, if you want to track mouse position you have to enable mouseTracking , otherwise the move events won't be triggered (though QEvent::Enter and QEvent::Leave will, which are the ones that indicates the mouse has entered or left the widget).

Here a minimal example of how to do it:

MyWidget::MyWidget(QWidget *parent)
  : QWidget(parent)
{
  m_label = new QLabel("Hello world!");
  m_label->setObjectName("m_label");
  m_label->installEventFilter(this);
  m_label->setMouseTracking(true);

  auto hlayout = new QVBoxLayout();
  hlayout->addWidget(m_label);
  setLayout(hlayout);
}

bool MyWidget::eventFilter(QObject* sender, QEvent* event)
{
  if (sender == m_label) {
    qDebug() << sender->objectName() << event->type();

    if (event->type() == QEvent::Enter) {
      qDebug() << "mouse on label name";
    } else if (event->type() == QEvent::Leave) {
      qDebug() << "mouse not on label name";
    }
  }

  return QWidget::eventFilter(sender, event);
}

The full working example is available in GitHub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM