头文件包含
#include <WinSock2.h>
#include <windows.h>
#include <QMainWindow>
#include <QFile>
#include <QtCore>
#include <QtGui>
#include <QMenu>
#include <QDesktopWidget>
#ifdef Q_OS_WIN
#include <qt_windows.h>
#include <Windowsx.h>
#endif
重写事件函数
通过重写mousePressEvent、mouseReleaseEvent、mouseMoveEvent控制鼠标按下、移动和释放,实现对窗口的移动效果。通过重写nativeEvent来监听windows的WM_NCHITTEST消息,实现对无边框窗体的缩放效果。
/*************************
* 鼠标左键被按下
* ***********************/
void MyCommonUI::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_bMousePress = true;
m_ptMove = event->pos();
}
return QWidget::mousePressEvent(event);
}
/*************************
* 鼠标左键按住拖动
* ***********************/
void MyCommonUI::mouseMoveEvent(QMouseEvent *event)
{
//若鼠标左键被按下
if(m_bMousePress)
{
//鼠标相对于屏幕的位置
QPoint move_pos = event->globalPos();
//移动主窗体位置
this->move(move_pos - m_ptMove);
}
event->accept();
return QWidget::mouseMoveEvent(event);
}
/*************************
* 释放鼠标
* ***********************/
void MyCommonUI::mouseReleaseEvent(QMouseEvent *event)
{
m_bMousePress = false;
return QWidget::mouseReleaseEvent(event);
}
/*************************
* nativeEvent获取windows的事件处理,为了让无边框窗体还能正常的缩放
* ***********************/
bool MyCommonUI::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
int m_nBorder = 5;
Q_UNUSED(eventType)
MSG *param = static_cast<MSG *>(message);
switch (param->message)
{
case WM_NCHITTEST:
{
int nX = GET_X_LPARAM(param->lParam) - this->geometry().x();
int nY = GET_Y_LPARAM(param->lParam) - this->geometry().y();
*result = HTCAPTION;
// if mouse in the border of mainframe,we zoom mainframe
if ((nX > 0) && (nX < m_nBorder))
*result = HTLEFT;
if ((nX > this->width() - m_nBorder) && (nX < this->width()))
*result = HTRIGHT;
if ((nY > 0) && (nY < m_nBorder))
*result = HTTOP;
if ((nY > this->height() - m_nBorder) && (nY < this->height()))
*result = HTBOTTOM;
if ((nX > 0) && (nX < m_nBorder) && (nY > 0)
&& (nY < m_nBorder))
*result = HTTOPLEFT;
if ((nX > this->width() - m_nBorder) && (nX < this->width())
&& (nY > 0) && (nY < m_nBorder))
*result = HTTOPRIGHT;
if ((nX > 0) && (nX < m_nBorder)
&& (nY > this->height() - m_nBorder) && (nY < this->height()))
*result = HTBOTTOMLEFT;
if ((nX > this->width() - m_nBorder) && (nX < this->width())
&& (nY > this->height() - m_nBorder) && (nY < this->height()))
*result = HTBOTTOMRIGHT;
if (*result == HTCAPTION)
{
return false;
}
return true;
}
}
return QWidget::nativeEvent(eventType, message, result);
}