QLabel响应鼠标单击消息

一般使用QLabel显示验证码比较方便,然后在图片上单击刷新验证码,这是最基本的功能,但是QLabel默认是没有鼠标单击的信号,网络上好多文章都是继承QLabel,然后重载event方法,可是我就为了一个单击事件,没必要这么大费周章。这是可以用到eventFilter,函数原型:

bool eventFilter(QObject * watched, QEvent * event);

需要在父类中为QLabel安插过滤器,这个函数才会被调用

m_pLabelImage->installEventFilter(this);

这样QLabel的所有消息都会经过eventFilter函数,如下是一种实现。

 1 bool LoginDialog::eventFilter(QObject * watched, QEvent * event)
 2 {
 3     if (watched == m_pLabelImage)
 4     {
 5         if (event->type() == QEvent::MouseButtonPress)
 6         {
 7             update_rand_image();  //单击刷新验证码
 8         }
 9     }
10     return QDialog::eventFilter(watched, event);
11 }
原文地址:https://www.cnblogs.com/lniwn/p/3373185.html