經過前兩節內容,咱們實現了自定義窗體的移動,以及自定義標題欄-用來顯示窗體的圖標、標題,以及控制窗體最小化、最大化、關閉。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,若是須要跨平臺的話,須要本身處理各類事件,並且得考慮的很全面。接口
原文做者:一去丶二三裏
做者博客:去做者博客空間