无边框窗口、控件的事件处理之nativeEvent

自定义窗口控件的无边框,窗口事件由于没有系统自带边框,无法实现拖拽拉伸等事件的处理,一种方法就是重新重写主窗口的鼠标事件,一种时通过nativeEvent事件处理。重写事件比较繁琐,个人喜欢nativeEvent处理,nativeEvent事件的处理其实也就是把窗口边界的事件转化为Windows的窗口事件.两种方式各有优缺点。例子如下:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 

class MainWindow : public QLabel
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

public:
    bool nativeEvent(const QByteArray &eventType, void *message, long *result);
};

#endif // MAINWINDOW_H

mainwindow.cpp 

#include "mainwindow.h"

#include 
#include 

MainWindow::MainWindow(QWidget *parent)
    : QLabel(parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setMinimumSize(45,45);
    this->setStyleSheet("background:#ff0000");
}

MainWindow::~MainWindow()
{

}

bool MainWindow::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(this->childAt(xPos,yPos) == 0)
        {
            *result = HTCAPTION;
        }else{
            return false;
        }

        if(xPos > 0 && xPos < 8)
            *result = HTLEFT;
        if(xPos > (this->width() - 8) && xPos < (this->width() - 0))
            *result = HTRIGHT;
        if(yPos > 0 && yPos < 8)
            *result = HTTOP;
        if(yPos > (this->height() - 8) && yPos < (this->height() - 0))
            *result = HTBOTTOM;
        if(xPos > 18 && xPos < 22 && yPos > 18 && yPos < 22)
            *result = HTTOPLEFT;
        if(xPos > (this->width() - 22) && xPos < (this->width() - 18) && yPos > 18 && yPos < 22)
            *result = HTTOPRIGHT;
        if(xPos > 18 && xPos < 22 && yPos > (this->height() - 22) && yPos < (this->height() - 18))
            *result = HTBOTTOMLEFT;
        if(xPos > (this->width() - 22) && xPos < (this->width() - 18) && yPos > (this->height() - 22) && yPos < (this->height() - 18))
            *result = HTBOTTOMRIGHT;
        return true;
    }

    return false;
}

main.cpp

#include 
#include 
#include "mainwindow.h"
#include "form.h"

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

    return a.exec();
}

 

 

你可能感兴趣的:(Qt,nativeEvent)