最终的效果是这样的:
头文件:
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected:
void paintEvent(QPaintEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseReleaseEvent(QMouseEvent *event) override;
private:
Ui::Widget *ui;
bool mIsHoveringOnCloseButton;
bool mIsPressed;
QPointF mPressedPos;
};
CPP文件:
#include "Widget.h"
#include "ui_Widget.h"
#include <QPaintEvent>
#include <QPainter>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget),mIsHoveringOnCloseButton(false),mIsPressed(false)
{
ui->setupUi(this);
setWindowFlag(Qt::FramelessWindowHint);
setMouseTracking(true);
}
void Widget::mouseReleaseEvent(QMouseEvent *event){
mIsPressed = false;
QWidget::mouseReleaseEvent(event);
}
void Widget::mousePressEvent(QMouseEvent *event){
if(event){
mIsPressed = true;
mPressedPos = event->pos();
if(mIsHoveringOnCloseButton){
this->close();
return;
}
}
QWidget::mousePressEvent(event);
}
void Widget::mouseMoveEvent(QMouseEvent *event){
if(event){
if(mIsPressed){
auto pos = event->globalPos();
auto delta = pos - mPressedPos ;
this->move(delta.toPoint() );
}
else{
auto pos = event->pos();
const auto x = pos.x();
const auto y = pos.y();
if(x >= this->width() - 32 && x <= this->width() &&
y >= 0 && y <= 32){
if(!mIsHoveringOnCloseButton){
mIsHoveringOnCloseButton = true;
update();
}
}
else{
if(mIsHoveringOnCloseButton){
mIsHoveringOnCloseButton = false;
update();
}
}
}
}
QWidget::mouseMoveEvent(event);
}
void Widget::paintEvent(QPaintEvent *event) {
if(event){
QPainter painter(this);
auto titleRect = event->rect();
titleRect.setHeight(40);
painter.setBrush(QColor("darkgray"));
painter.setPen(Qt::NoPen);
painter.drawRect(titleRect);
auto closeButtonRect = event->rect();
closeButtonRect.setLeft(width() - 32);
closeButtonRect.setHeight(40);
QFont font;
font.setPixelSize(26);
painter.setFont(font);
if(mIsHoveringOnCloseButton)
painter.setPen(QColor("magenta"));
else
painter.setPen(QColor("black"));
painter.setBrush(Qt::NoBrush);
painter.drawText(closeButtonRect, "✘");
}
}
Widget::~Widget()
{
delete ui;
}