简体   繁体   English

Qt:enterEvent和leaveEvent不起作用

[英]Qt: enterEvent and leaveEvent doesnt work

I have strange problem with mouse events in Qt. 我在Qt中的鼠标事件有奇怪的问题。 I have following code: 我有以下代码:

#ifndef QSTONEFIELD_HPP_
#define QSTONEFIELD_HPP_

#include <QtGui>
#include <QWidget>

class QStoneField : public QWidget
{
    Q_OBJECT

private:
    // some stuff

public:
    // some methods

protected:
    void paintEvent(QPaintEvent *event);   
    virtual void mousePressEvent(QMouseEvent * event);
    virtual void enterEvent(QMouseEvent * event);
    virtual void leaveEvent(QMouseEvent * event);

signals:

public slots:

};

#endif

And in second file I have: 在第二个文件中我有:

#include "qstonefield.hpp"
// FIXME temporary include
#include <iostream>
using namespace std;

// some other methods ..

void QStoneField::mousePressEvent(QMouseEvent * event)
{
    cout << "CLICK!" << endl << flush;
}

void QStoneField::enterEvent(QMouseEvent * event)
{
    cout << "ENTER!" << endl << flush;
}

void QStoneField::leaveEvent(QMouseEvent * event)
{
    cout << "LEAVE!" << endl << flush;
}

And now when I compile and run it, I can invoke mousePressEvent because program prints "CLICK!", but when I am crossing the widget by mouse, it prints just nothing. 现在当我编译并运行它时,我可以调用mousePressEvent,因为程序打印“CLICK!”,但是当我用鼠标穿过小部件时,它什么也没打印。 Of course in main.cpp I didnt forget to stone.setMouseTracking(true). 当然在main.cpp中我没有忘记stone.setMouseTracking(true)。

Why enterEvent and leaveEvent doesnt work? 为什么enterEvent和leaveEvent不起作用? It should work according to documentation. 它应该根据文档工作。 Thanks in advance! 提前致谢!

The signature of your function should be: 您的功能的签名应该是:

virtual void QStoneField::enterEvent(QEvent * event);
virtual void QStoneField::leaveEvent(QEvent * event);

You are simply using the wrong parameter for the function which means the one from Qwidget are not overwritten. 您只是为函数使用了错误的参数,这意味着Qwidget中的参数不会被覆盖。

I recommend you to consider what the default implementation does, for example : 我建议您考虑默认实现的作用,例如:

virtual void QStoneField::leaveEvent(QEvent * event){
       //do my own things
       QWidget::leaveEvent(event);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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