QT实现完美无边框窗口(可拖动,可调整大小)

效果如下: 

QT实现完美无边框窗口(可拖动,可调整大小)_第1张图片

 只需定义 nativeEvent 事件即可完成这样的功能 ,但要注意的是,这是通过Windows api实现的。

样例如下:(注意头文件)

framelesswidget.h

#ifndef FRAMELESSWIDGET_H
#define FRAMELESSWIDGET_H

#include       
#include         //注意头文件
#include 
#include 
class FramelessWidget : public QWidget
{
    Q_OBJECT

public:
    FramelessWidget(QWidget *parent = 0);
    ~FramelessWidget();
protected:
    bool nativeEvent(const QByteArray &eventType, void *message, long *result);
    void mousePressEvent(QMouseEvent *e);
    void mouseMoveEvent(QMouseEvent *e);
private:
    int boundaryWidth;
    QPoint clickPos;
};

#endif // FRAMELESSWIDGET_H

framelesswidget.cpp 

#include "framelesswidget.h"

FramelessWidget::FramelessWidget(QWidget *parent)
    : QWidget(parent)
{
    boundaryWidth=4;                                    //设置触发resize的宽度
    this->setWindowFlags(Qt::FramelessWindowHint);      //设置为无边框窗口
    this->setMinimumSize(45,45);                        //设置最小尺寸
    this->setStyleSheet("background:#D1EEEE");          //设置背景颜色
}
FramelessWidget::~FramelessWidget()
{

}

bool FramelessWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = (MSG*)message;   
    switch(msg->message)
        {
        case WM_NCHITTEST:
            int xPos = GET_X_LPARAM(msg->lParam) - this->frameGeometry().x();
            int yPos = GET_Y_LPARAM(msg->lParam) - this->frameGeometry().y();
            if(xPos < boundaryWidth && yPos=width()-boundaryWidth&&yPos=height()-boundaryWidth)         //左下角
                *result = HTBOTTOMLEFT;
            else if(xPos>=width()-boundaryWidth&&yPos>=height()-boundaryWidth)//右下角
                *result = HTBOTTOMRIGHT;
            else if(xPos < boundaryWidth)                                     //左边
                *result =  HTLEFT;
            else if(xPos>=width()-boundaryWidth)                              //右边
                *result = HTRIGHT;
            else if(yPos=height()-boundaryWidth)                             //下边
                *result = HTBOTTOM;
            else              //其他部分不做处理,返回false,留给其他事件处理器处理
               return false;
            return true;
        }
        return false;         //此处返回false,留给其他事件处理器处理
}


void FramelessWidget::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::LeftButton)
        clickPos=e->pos();
}
void FramelessWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(e->buttons()&Qt::LeftButton)
        move(e->pos()+pos()-clickPos);
}

main.cpp 

#include "framelesswidget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    FramelessWidget w;
    w.show();

    return a.exec();
}

 

你可能感兴趣的:(Qt)