EventFilter:多用于没有点击信号(clicked)的部件添加点击信号
操作
- 首先给需要添加事件过滤器的部件注册监听对象;
对象名->installEventFilter(this);- 重写
eventFilter(QObject *obj, QEvent *event)函数进行处理。
例:给没有clicked信号的QComboBox部件增加点击事件,点击QComboBox刷新下拉选项
1 在头文件中添加:
public slots:
bool eventFilter(QObject *watched, QEvent *event);
2 在构造函数中安装QComboBox的事件过滤器:
ui->serialPortCbx->installEventFilter(this);
3 实现函数
bool Serial_port_test::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress){
if(watched == ui->serialPortCbx){
QComboBox * combobox = qobject_cast<QComboBox *>(watched);
combobox->clear();
combobox->addItems("test 1");
combobox->addItems("test 2");
}
return true;
}
return false;
}
本文介绍如何通过EventFilter为不支持clicked信号的Qt组件如QComboBox添加点击事件。通过安装事件过滤器并重写eventFilter函数,可以实现在点击组件时刷新下拉选项等自定义行为。
7121

被折叠的 条评论
为什么被折叠?



