经过前两节内容,咱们实现了自定义窗体的移动,以及自定义标题栏-用来显示窗体的图标、标题,以及控制窗体最小化、最大化、关闭。windows
在这以后,咱们还缺乏窗体的缩放-当鼠标移动到窗体的边框-左、上、右、下、左上角、左下角、右上角、右下角时候,鼠标变为相应的样式,而且窗体能够随着鼠标拖动而进行放大、缩小。markdown
包含头文件与须要用到的库this
#ifdef Q_OS_WIN
#include <qt_windows.h>
#include <Windowsx.h>
#endif
使用nativeEvent进行窗体缩放spa
bool Widget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
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();
// 鼠标区域位于标题栏按钮之上,则不进行处理
QList<QPushButton *> buttons = m_pTitleBar->findChildren<QPushButton *>();
foreach (QPushButton *pButton, buttons)
{
if (pButton->geometry().contains(QPoint(nX, nY)))
{
*result = HTCLIENT;
return true;
}
}
// 鼠标区域位于标题栏中,进行移动
if (nX >= m_nBorder && nX <= this->width() - m_nBorder
&& nY >= m_nBorder && nY <= m_pTitleBar->height())
{
*result = HTCAPTION;
return true;
}
// 鼠标区域位于窗体边框,进行缩放
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;
return true;
}
}
return QWidget::nativeEvent(eventType, message, result);
}
Qt5与Qt4其中的一个区别就是用nativeEvent代替了winEvent。.net
nativeEvent主要用于进程间通讯-消息传递。在这里咱们主要进行窗体缩放,其中还添加了一些限制,好比:code
使用这种方式后,窗体就能够随意缩放了,并且能够去掉标题栏中控制界面移动的代码-在mousePressEvent中使用SendMessage来进行移动。blog
固然,这种实现只能在Windows下使用,由于用的是Win API,若是须要跨平台的话,须要本身处理各类事件,并且得考虑的很全面。接口
原文做者:一去丶二三里
做者博客:去做者博客空间