我们在做项目的时候,有一个这样的需求,就是一个按钮,鼠标放上去之后,就会弹出一张图片,鼠标移开,图片就消失。
比如这样的按钮,
鼠标放上去之后,就会弹出对话框
该怎么做呢?
其中,
1.那个带图标的按钮, 其实是个QToolButton, 可以设置前面图标,后面文字。
2.使用QLabel 显示图片
m_pStandardLabel = new QLabel(this);QPixmap pixmap(qApp->applicationDirPath() + "/scoreStandard.png");m_pStandardLabel->setPixmap(pixmap);m_pStandardLabel->resize(619, 471);m_pStandardLabel->hide();
3.安装事件过滤器(需要给QToolButton 和显示图片的QLabel都要安装)
ui->scoreStandardBtn->installEventFilter(this);m_pStandardLabel->installEventFilter(this);
4.重写事件过滤器
bool eventFilter(QObject *watched, QEvent *event);
bool QcTaskDetailForm::eventFilter(QObject *watched, QEvent *event)
{if(ui->scoreStandardBtn == watched || m_pStandardLabel == watched) {if(QEvent::Enter == event->type()) { //鼠标进入if (m_pStandardLabel->isHidden()) { //已经隐藏就显示出来m_pStandardLabel->show();QPoint point = ui->scoreStandardBtn->pos();point.rx() = point.x() - m_pStandardLabel->width() + 120;point.ry() = point.y() + ui->scoreStandardBtn->height() + 40;m_pStandardLabel->move(point);m_pStandardLabel->raise();//显示最顶层return true;}}else if (QEvent::Leave == event->type()) { //鼠标离开if (!m_pStandardLabel->isHidden()) {if(!ui->scoreStandardBtn->geometry().contains(this->mapFromGlobal(QCursor::pos())) //判断鼠标是否在控件上&&!m_pStandardLabel->geometry().contains(this->mapFromGlobal(QCursor::pos())) ){m_pStandardLabel->hide();return true;}}}}return QWidget::eventFilter(watched, event);
}