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;
}