Qt鼠标悬停+悬浮窗口

Qt鼠标悬停+悬浮窗口

  • 新建一个C++类:mouseHover
  • 新建一个Qt界面类:QRImage
  • 主界面
  • 效果

这两个功能,有很多办法可以实现,这里记一下笔者常用的。

新建一个C++类:mouseHover

mouseHover.h

#ifndef MOUSEHOVER_H
#define MOUSEHOVER_H

#include 

class mouseHover : public QObject
{
    Q_OBJECT
public:
    mouseHover();
signals:
    void signal_sendBtnObj(QObject*, QString);
protected:
    bool eventFilter(QObject *obj, QEvent *event) override;
};

#endif // MOUSEHOVER_H

mouseHover.cpp

#include "mousehover.h"
#include 
#include 
mouseHover::mouseHover()
{

}

bool mouseHover::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::Enter){//鼠标进入控件
        emit signal_sendBtnObj(obj, obj->objectName());
        return true;
    }else if (event->type() == QEvent::Leave){//鼠标离开控件
        emit signal_sendBtnObj(obj, "mouse out");
        return true;
    }else{
        return  QObject::eventFilter(obj, event);
    }
}

新建一个Qt界面类:QRImage

QRImage.h

#ifndef QRIMAGE_H
#define QRIMAGE_H

#include 

namespace Ui {
class QRImage;
}

class QRImage : public QWidget
{
    Q_OBJECT

public:
    explicit QRImage(QWidget *parent = nullptr);
    ~QRImage();
public slots:
    void slots_showQR(QString);

private:
    Ui::QRImage *ui;
};

#endif // QRIMAGE_H

QRImage.cpp

#include "qrimage.h"
#include "ui_qrimage.h"
#include 

QRImage::QRImage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QRImage)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);//无边框
}

QRImage::~QRImage()
{
    delete ui;
}

void QRImage::slots_showQR(QString mes)
{
    if (mes == "quit")
        this->close();
    else if (mes == "BAIDU")
        ui->label->setText("www.baidu.com");
}

主界面

MainWindow.h

#include "mousehover.h"
#include "qrimage.h"
    QLabel *label_mes;//一个标签
    QStatusBar *qstBar;//状态栏
    QRImage *qr;//悬浮窗口
signals:
    void signal_showQR(QString);
public slots:
    void slot_BtnObj(QObject*, QString);

MainWindow.cpp

/// 鼠标悬停
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qr = new QRImage;//实例化
    connect(this, &MainWindow::signal_showQR, qr, &QRImage::slots_showQR);
    mouseHover *mmHover = new mouseHover();//实例化
    connect(mmHover, &mouseHover::signal_sendBtnObj, this, &MainWindow::slot_BtnObj);//连接信号槽
    //状态栏
    qstBar = this-->statusBar();
    label_mes = new QLabel("将鼠标移动到这里", this);
    label_mes->installEventFilter(mmHover);
    qstBar->addWidget(label_mes);//添加到状态栏左侧
    qstBar->addPermanentWidget(label_mes);//添加到状态栏右侧    

void MainWindow::slot_BtnObj(QObject *objm QString objName)
{
    if (objName == "mouse out"){
        label_mes->setText("鼠标已离开");
        emit signal_showQR("quit");
    }else{
        if (objName == label_mes){
            label_mes->setText("鼠标已进入");
            qr->show();
            emit signal_showQR("BAIDU");
        }
    }
}
}

效果

Qt鼠标悬停+悬浮窗口_第1张图片

你可能感兴趣的:(QT,ui,qt,开发语言)