【Qt】Qt之自定义界面(窗体缩放)【转】

简述

通过前两节内容,我们实现了自定义窗体的移动,以及自定义标题栏-用来显示窗体的图标、标题,以及控制窗体最小化、最大化、关闭。

在这之后,我们还缺少窗体的缩放-当鼠标移动到窗体的边框-左、上、右、下、左上角、左下角、右上角、右下角时候,鼠标变为相应的样式,并且窗体可以随着鼠标拖动而进行放大、缩小。

效果

这里写图片描述

窗体缩放

实现

包含头文件与需要用到的库

#ifdef Q_OS_WIN
#include <qt_windows.h>
#include <Windowsx.h>
#endif

使用nativeEvent进行窗体缩放

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。

nativeEvent主要用于进程间通信-消息传递。在这里我们主要进行窗体缩放,其中还添加了一些限制,比如:

  1. 鼠标区域位于标题栏按钮之上,则不进行处理。
  2. 鼠标区域位于标题栏中,进行移动。

使用这种方式后,窗体就可以随意缩放了,而且可以去掉标题栏中控制界面移动的代码-在mousePressEvent中使用SendMessage来进行移动。

当然,这种实现只能在Windows下使用,因为用的是Win API,如果需要跨平台的话,需要自己处理各种事件,而且得考虑的很全面。


原文作者:一去丶二三里
作者博客:去作者博客空间
posted @ 2016-01-21 18:50  芝麻学问  阅读(1079)  评论(0编辑  收藏  举报