Qt:自定义tooltip

在主窗口里获取鼠标的悬浮事件

_customTooltip是我定义在私有变量里的

 AbnormalToolTipWidget *_customTooltip = nullptr;

bool RobotAbnormalBtns::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::HoverEnter) {
        // 鼠标悬浮时显示自定义的工具提示
        if (!_customTooltip) {
            _customTooltip = new AbnormalToolTipWidget(this);
        }

        _customTooltip->addAbnormalInfo(/* 这里填入向widget传的数据*/);

        QPoint pos = mapToGlobal(static_cast(obj)->pos());
        _customTooltip->move(mapToGlobal(QPoint(this->rect().right()+15,this->rect().center().y()-74))); // 设置提示显示的位置

        _customTooltip->show();
        _customTooltip->raise();
    } else if (event->type() == QEvent::HoverLeave) {
        if (_customTooltip) {
            _customTooltip->hide();
        }
    }
    return QObject::eventFilter(obj, event);
}

AbnormalToolTipWidget:

#include 
#include 

namespace Ui {
class AbnormalToolTipWidget;
}

class AbnormalToolTipWidget : public QWidget
{
    Q_OBJECT

public:
    explicit AbnormalToolTipWidget(QWidget *parent = nullptr);
    ~AbnormalToolTipWidget();
    void addAbnormalInfo(QVariantList infoList);
private:
    Ui::AbnormalToolTipWidget *ui;
};
#include "AbnormalToolTipWidget.h"
#include "ui_AbnormalToolTipWidget.h"
#include "PublicClass/StyleObject.h"
#include "UiClass.h"

AbnormalToolTipWidget::AbnormalToolTipWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AbnormalToolTipWidget)
{
    ui->setupUi(this);
    // 设置自定义提示框的大小和外观
    setWindowFlags(Qt::ToolTip);
    setAttribute(Qt::WA_OpaquePaintEvent, false);//这里不设置为false,会有显示问题
    setAutoFillBackground(true);

    /*这里就可以开始设计自定义的内容了*/

    // 设置自定义提示框的大小
    resize(553, 60);

}

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

void AbnormalToolTipWidget::addAbnormalInfo(QVariantList infoList)
{
      //这是我定义的 外部传数据的函数  根据外部数据修改显示内容
}

你可能感兴趣的:(qt,c++)