Qt 自定义全局悬浮置顶按钮
效果
使用示例
ResetButton* resetBtn;
resetBtn = new ResetButton();
resetBtn->show();
resetBtn->move(QPoint(1000, 800));
connect(resetBtn, &ResetButton::clicked, this, &MainWindow::Reset);
自行加入图片,透明底即可
源码
ResetButton.h
#pragma once#include <QWidget>class ResetButton : public QWidget
{Q_OBJECTpublic:ResetButton(QWidget *parent = nullptr);~ResetButton();signals:void clicked();protected:virtual void paintEvent(QPaintEvent *e) override;virtual void mousePressEvent(QMouseEvent *e) override;virtual void mouseReleaseEvent(QMouseEvent *e) override;virtual void mouseMoveEvent(QMouseEvent *e) override;private:QPixmap mPixNormal;QPixmap mPixClicked;QPoint mousePoint;bool right_pressed = false;bool left_pressed = false;
};
ResetButton.cpp
#include "ResetButton.h"
#include <QPaintEvent>
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>ResetButton::ResetButton(QWidget *parent): QWidget(parent)
{//设置无边框,并显示在最上层this->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint | Qt::FramelessWindowHint);this->resize(100, 100);setAttribute(Qt::WA_TranslucentBackground, true);mPixNormal = QPixmap(":/resource/reset.png");mPixClicked = QPixmap(":/resource/reset_clicked.png");
}ResetButton::~ResetButton()
{
}void ResetButton::paintEvent(QPaintEvent * e)
{QPainter p(this);
#ifdef Q_OS_LINUXp.setPen(Qt::NoPen);p.setBrush(Qt::white);p.drawRect(this->rect()); // Linux fill white
#endifp.drawPixmap(this->rect(), left_pressed ? mPixClicked : mPixNormal);p.end();
}void ResetButton::mousePressEvent(QMouseEvent * e)
{if (e->button() == Qt::LeftButton) {left_pressed = true;emit clicked();this->update();}if (e->button() == Qt::RightButton) {right_pressed = true;mousePoint = e->globalPos() - this->pos();}
}void ResetButton::mouseReleaseEvent(QMouseEvent * e)
{if (e->button() == Qt::LeftButton) {left_pressed = false;this->update();}if (e->button() == Qt::RightButton) {right_pressed = false;}
}void ResetButton::mouseMoveEvent(QMouseEvent * e)
{if (right_pressed) {move(e->globalPos() - mousePoint);}
}