QT 鼠标移到按钮上,就弹出对话框,移开,对话框就消失

    我们在做项目的时候,有一个这样的需求,就是一个按钮,鼠标放上去之后,就会弹出一张图片,鼠标移开,图片就消失。

比如这样的按钮,

鼠标放上去之后,就会弹出对话框



该怎么做呢?

其中,

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


  • 18
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Qt中,可以通过点击按钮来实现画面移动固定距离的效果。下面是一个简单的示例代码: 首先,需要导入Qt中相关的模块: ```cpp #include <QtWidgets> ``` 然后,在主窗口类中,定义一个成员变量来保存画面的当前位置,例如: ```cpp private: int currentPosition = 0; ``` 在窗口构造函数中,创建一个按钮并连接到槽函数: ```cpp MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // 创建按钮 QPushButton *button = new QPushButton("移动", this); // 连接按钮的点击事件到自定义的槽函数 connect(button, &QPushButton::clicked, this, &MainWindow::moveScreen); } ``` 接下来,实现槽函数`moveScreen`,该函数会使画面移动固定距离: ```cpp void MainWindow::moveScreen() { // 移动画面的代码 // 假设每次点击按钮移动10个像素的距离 currentPosition += 10; // 更新画面位置 // 这里的 QWidget 是指需要移动的窗口对象,可以根据实际情况修改 QWidget *screen = this; // 假设主窗口需要移动 screen->move(currentPosition, screen->y()); } ``` 在上述代码中,通过增加`currentPosition`的值来使画面向右移动,然后通过`move`函数将主窗口的位置更新为新的横坐标,从而实现画面移动固定距离的效果。 当点击按钮时,槽函数`moveScreen`会被调用,画面将会以固定距离移动。每次点击按钮,都会使画面向右移动10个像素的距离。你可以根据需要修改距离值。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值