c++ qt,widget窗口上有一个QLabel控件,使用eventFilter函数拦截双击QLabel控件事件,并结合event()函数使用,给出完成的例子
时间: 2024-02-17 10:00:51 浏览: 83
好的,下面是一个完整的示例代码:
mywidget.h文件:
```cpp
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>
namespace Ui {
class MyWidget;
}
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = nullptr);
~MyWidget();
private:
Ui::MyWidget *ui;
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
};
#endif // MYWIDGET_H
```
mywidget.cpp文件:
```cpp
#include "mywidget.h"
#include "ui_mywidget.h"
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MyWidget)
{
ui->setupUi(this);
ui->label->installEventFilter(this); // 将事件过滤器安装到QLabel上
}
MyWidget::~MyWidget()
{
delete ui;
}
bool MyWidget::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->label && event->type() == QEvent::MouseButtonDblClick) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
qDebug() << "Label double clicked!";
qDebug() << "Event position:" << mouseEvent->pos();
return true;
}
}
return QObject::eventFilter(obj, event);
}
```
其中,mywidget.ui文件中添加了一个QLabel控件,并将其命名为label。
在项目.pro文件中添加:
```cpp
QT += widgets
```
这个示例代码可以实现当双击QLabel时,在控制台输出信息。你可以根据自己的需求修改eventFilter函数中的代码。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)