我在Qt中的鼠标事件有奇怪的问题.我有以下代码:
#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
在第二个文件中我有:
#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;
}
现在当我编译并运行它时,我可以调用mousePressEvent,因为程序打印“CLICK!”,但是当我用鼠标穿过小部件时,它什么也没打印.
当然在main.cpp中我没有忘记stone.setMouseTracking(true).
为什么enterEvent和leaveEvent不起作用?它应该根据文档工作.
提前致谢!
解决方法:
您的功能的签名应该是:
virtual void QStoneField::enterEvent(QEvent * event);
virtual void QStoneField::leaveEvent(QEvent * event);
您只是为函数使用了错误的参数,这意味着Qwidget中的参数不会被覆盖.
我建议您考虑默认实现的作用,例如:
virtual void QStoneField::leaveEvent(QEvent * event){
//do my own things
QWidget::leaveEvent(event);
}