Qt 自定义全局悬浮置顶按钮

Qt 自定义全局悬浮置顶按钮

效果

Qt 自定义全局悬浮置顶按钮_第1张图片

使用示例

ResetButton* resetBtn;
resetBtn = new ResetButton();
resetBtn->show();
resetBtn->move(QPoint(1000, 800));
connect(resetBtn, &ResetButton::clicked, this, &MainWindow::Reset);

在这里插入图片描述
自行加入图片,透明底即可

源码

ResetButton.h

#pragma once

#include 

class ResetButton : public QWidget
{
	Q_OBJECT

public:
	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 
#include 
#include 
#include 

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_LINUX
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::white);
    p.drawRect(this->rect()); // Linux fill white
#endif

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



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