Qt无边框窗口移动、拉伸、缩放
时间: 2023-09-09 16:11:34 浏览: 455
在Qt中实现无边框窗口移动、拉伸、缩放需要使用QWidget的一些事件和函数。具体实现步骤如下:
1.设置无边框窗口
在QWidget中通过设置setWindowFlags函数来实现无边框窗口。例如:
```
setWindowFlags(Qt::FramelessWindowHint);
```
2.移动窗口
在QWidget中通过重写鼠标按下、移动、释放事件来实现窗口移动。例如:
```
void mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_isPressed = true;
m_startPoint = event->globalPos() - this->geometry().topLeft();
}
}
void mouseMoveEvent(QMouseEvent *event)
{
if (m_isPressed)
{
this->move(event->globalPos() - m_startPoint);
}
}
void mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_isPressed = false;
}
}
```
其中m_isPressed记录鼠标左键是否按下,m_startPoint记录鼠标按下时的位置与窗口左上角的距离,this->move函数实现窗口移动。
3.拉伸窗口
在QWidget中通过重写鼠标按下、移动、释放事件来实现窗口拉伸。例如:
```
void mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_isPressed = true;
m_startPoint = event->globalPos();
m_startGeometry = this->geometry();
}
}
void mouseMoveEvent(QMouseEvent *event)
{
if (m_isPressed)
{
QPoint diff = event->globalPos() - m_startPoint;
if (m_resizeDir == RESIZE_DIR_LEFT_TOP)
{
this->setGeometry(m_startGeometry.x() + diff.x(), m_startGeometry.y() + diff.y(), m_startGeometry.width() - diff.x(), m_startGeometry.height() - diff.y());
}
else if (m_resizeDir == RESIZE_DIR_RIGHT_TOP)
{
this->setGeometry(m_startGeometry.x(), m_startGeometry.y() + diff.y(), m_startGeometry.width() + diff.x(), m_startGeometry.height() - diff.y());
}
else if (m_resizeDir == RESIZE_DIR_LEFT_BOTTOM)
{
this->setGeometry(m_startGeometry.x() + diff.x(), m_startGeometry.y(), m_startGeometry.width() - diff.x(), m_startGeometry.height() + diff.y());
}
else if (m_resizeDir == RESIZE_DIR_RIGHT_BOTTOM)
{
this->setGeometry(m_startGeometry.x(), m_startGeometry.y(), m_startGeometry.width() + diff.x(), m_startGeometry.height() + diff.y());
}
}
}
void mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_isPressed = false;
}
}
```
其中m_isPressed记录鼠标左键是否按下,m_startPoint记录鼠标按下时的位置,m_startGeometry记录窗口拉伸前的位置和大小,m_resizeDir记录拉伸方向(左上、右上、左下、右下),this->setGeometry函数实现窗口拉伸。
4.缩放窗口
在QWidget中通过重写wheelEvent事件来实现窗口缩放。例如:
```
void wheelEvent(QWheelEvent *event)
{
QPoint pos = event->pos();
if (event->delta() > 0)
{
this->resize(this->width() * 1.2, this->height() * 1.2);
}
else
{
this->resize(this->width() * 0.8, this->height() * 0.8);
}
QPoint newPos = this->mapFromGlobal(this->mapToGlobal(pos));
QPoint diff = newPos - pos;
this->move(this->x() - diff.x(), this->y() - diff.y());
}
```
其中event->delta()为正表示向上滚动,为负表示向下滚动,this->resize函数实现窗口缩放,this->mapFromGlobal和this->mapToGlobal函数用于将鼠标位置从全局坐标系转换为窗口坐标系,diff记录窗口缩放前后鼠标位置的差值,this->move函数实现窗口位置的调整。
以上就是在Qt中实现无边框窗口移动、拉伸、缩放的方法。
阅读全文