首页 > 技术文章 > QT笔记 -- (4) 为QLabel添加鼠标响应方法2

redips-l 2017-06-13 17:22 原文

1.实现 bool eventFilter(QObject *target,QEvent *event)

函数内容如下:

bool eventFilter(QObject *target,QEvent *event){
        if (target == ui.CurImageLabel){
            if (event->type() == QEvent::MouseButtonPress){
                float pox = ((QMouseEvent*)event)->pos().x();
                float poy = ((QMouseEvent*)event)->pos().y();
                if (this->curActionType > -1){
                    if (curActionType / 2 == 0){  //draw rect
                        if (curActionType == 0) {
                            _spos_[0] = pox / curImgLabelWidth, _spos_[1 ] = poy / curImgLabelHeight;
                            curActionType++;
                        }
                    }
                }
            }
        }
        //...
        return QMainWindow::eventFilter(target,event);
}

2.然后再注册响应的控件就行了

ui.CurImageLabel->installEventFilter(this);

推荐阅读