QT自定义UI组件_圆角窗口

实现思想:

  隐藏系统自带的边框, 并将背景颜色设置成透明, 在painter函数中绘制一个圆角矩形

如图:

 

 代码如下:  头文件

#ifndef ROUNDWIDGET_H
#define ROUNDWIDGET_H

#include <QWidget>

namespace Ui { class RoundWidget; }
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE

class RoundWidget : public QWidget
{
    Q_OBJECT

public:
    RoundWidget(QWidget *parent = nullptr);
    ~RoundWidget();

public:
    void paintEvent(QPaintEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);
private:
    void InitWidget();
private:
    QPoint m_LastPoint;
private:
    Ui::RoundWidget *ui;
};

  cpp文件: 用到了QPainter中的drawRoundRect函数

#include "roundwidget.h"
#include "ui_roundwidget.h"
#include <QPaintEvent>
#include <QMouseEvent>
#include <QResizeEvent>
#include <QPainter>
#include <QDebug>

RoundWidget::RoundWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RoundWidget)
{
    InitWidget();
    ui->setupUi(this);

}

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

void RoundWidget::InitWidget()
{
    //设置背景透明
    this->setAttribute(Qt::WA_TranslucentBackground);
    //去掉边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    //顶端显示
    //this->setWindowFlags(this->windowFlags()|Qt::WindowStaysOnTopHint);
    //最大化, 并遮挡任务栏
    //this->setWindowState(Qt::WindowFullScreen | Qt::WindowMaximized);
}

void RoundWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter paint(this);
    paint.setBrush(Qt::yellow);
    paint.setPen(QPen(Qt::transparent, 2, Qt::DashLine));
    QRect roundRect(rect().x() + 10, rect().y() +10, rect().width() -20, rect().height() - 20);
    paint.drawRoundRect(roundRect, 5, 5);
}

void RoundWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->globalX() - m_LastPoint.x();
    int dy = event->globalY() - m_LastPoint.y();
    move(x() + dx, y() + dy);
    m_LastPoint = event->globalPos();
}

void RoundWidget::mousePressEvent(QMouseEvent *event)
{
    m_LastPoint = event->globalPos();
}

  

posted @ 2020-08-05 15:19  Software_hul  阅读(582)  评论(0编辑  收藏  举报