QT自定义标题栏

QT

自定义标题栏

隐藏标题栏

    setWindowFlags(Qt::FramelessWindowHint | windowFlags());

窗口移动

方法1:

重写下面三个函数

void MyWidget::mousePressEvent(QMouseEvent *event)  
{  
    if (event->button() == Qt::LeftButton) {  
        m_bPressed = true;  
        m_StartPoint = event->globalPos() - this->pos();  
        event->accept();  
    }  
}  
  
void MyWidget::mouseMoveEvent(QMouseEvent *event)  
{         
    QPoint currentPoint = event->globalPos();
    if (m_bPressed)
    {  
        this->move(this->geometry().topLeft() + currentPoint - m_StartPoint);
    }  
}  
  
void MyWidget::mouseReleaseEvent(QMouseEvent *)  
{  
   if (event->button() == Qt::LeftButton)
    {
        m_bPressed = false;
    }
	return QWidget::mouseReleaseEvent(event);
}  

这种方式实现的窗口移动 每次move时都会触发事件,计算位置,移动窗口,重绘窗口效率并不高

方法2

windows平台下可以使用

void MyWidget::mousePressEvent(QMouseEvent *event)
{
    QRect rect = ui.widget_4->rect();

    if (event->button() == Qt::LeftButton)
    {
        
#ifdef Q_OS_WIN
        if (ReleaseCapture())
        {
            SendMessage((HWND)this->winId(), WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
        }
#endif // Q_OS_WIN  
    }
}

窗口移动到边缘半屏或者最大化

    //设置属性产生win窗体效果,移动到边缘半屏或者最大化等
    //设置以后会产生标题栏需要在下面拦截消息重新去掉
#ifdef Q_OS_WIN
    HWND hwnd = (HWND)this->winId();
    DWORD style = ::GetWindowLong(hwnd, GWL_STYLE);
    ::SetWindowLong(hwnd, GWL_STYLE, style | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CAPTION);
#endif

//在nativeEvent需要拦截消息WM_NCCALCSIZE
bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    Q_UNUSED(eventType);

    MSG *msg = static_cast(message);
    switch (msg->message)
    {
    case WM_NCCALCSIZE:
        *result = 0;
        return true;
    default:
        return false;
        break;
    }
    return false;
}

最小化

void MyWidget::slot_OnMinClicked()
{
    this->showMinimized();
}

关闭

void MyWidget::slot_OnCloseClicked()
{
    this->close();
}

最大化

void MyWidget::slot_OnMaxClicked()
{
    this->isMaximized() ? this->showNormal() : this->showMaximized();
}

你可能感兴趣的:(QT,qt,开发语言)