控件嵌套中的QT鼠标事件处理机制

想实现在层层布局的控件中,对最外层的QLabel上的鼠标事件实现tracking,即触发mouseMoveEvent的时候,不需要一直按着

前提:自定义控件,继承QLabel重写鼠标事件相应的方法
可参考:https://wiki.qt.io/Clickable_QLabel

否则label根本接受不到鼠标事件,谈什么label->setMouseTracking(true);而且,像label本身就在最外层的,也不需要层层都setMouseTracking(true);


好了,由于此前不知,鼠标事件都写好在MainWindow下重写mouseMoveEvent下了,迁移到在子控件label下处理,改动太大,于是想

  1. void Label::mousePressEvent(QMouseEvent *ev)里通过parent指针((MainWindow *)this->parent())->mousePressEvent(ev);调用void MainWindow::mousePressEvent(QMouseEvent *ev),发现即使类型转换能运行,实际上并没有调用成功
  2. 通过由外向内的setAttribute(Qt::WA_TransparentForMouseEvents);
tab_label->setAttribute(Qt::WA_TransparentForMouseEvents);
tab->setAttribute(Qt::WA_TransparentForMouseEvents);
ui->tabWidget->setAttribute(Qt::WA_TransparentForMouseEvents);
ui->centralWidget->setAttribute(Qt::WA_TransparentForMouseEvents);

能基本实现,但是也让tab下的其他控件的鼠标事件失效了
3. 最后通过QT的事件过滤器实现
这里写图片描述
具体可参考https://blog.csdn.net/chenlong12580/article/details/7724010
就是让子控件label加一句label->installEventFilter(this);//注册事件监听器
MainWindow实现监听

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==cur->tab_label){
        QMouseEvent * mouseEvent=static_cast<QMouseEvent*>(event);
        if(event->type()==QEvent::MouseButtonPress){
            mousePressEvent(mouseEvent);
        }else if(event->type()==QEvent::MouseMove){
            mouseMoveEvent(mouseEvent);
        }
        //return true;
    }
    return QMainWindow::eventFilter(watched, event);
}

由于我直接把label上所有的event,上来就直接转成鼠标事件,不注释return true的话,鼠标事件是理想了,图片加载不出来,不知道是不是因为加载图片也会被监听到什么event

猜你喜欢

转载自blog.csdn.net/qq_36620040/article/details/82423381