Qt去除标题栏,且可以移动和缩放界面的代码
时间: 2024-05-02 22:21:06 浏览: 18
以下是去除标题栏并实现移动和缩放界面的Qt代码:
mainwindow.h
```cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private:
QPoint m_dragPos;
bool m_dragging;
};
#endif // MAINWINDOW_H
```
mainwindow.cpp
```cpp
#include "mainwindow.h"
#include <QMouseEvent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragPos = event->globalPos() - frameGeometry().topLeft();
m_dragging = true;
event->accept();
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (m_dragging && event->buttons() & Qt::LeftButton) {
move(event->globalPos() - m_dragPos);
event->accept();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragging = false;
event->accept();
}
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
Q_UNUSED(event);
update();
}
```
在这个示例中,我们使用 `setWindowFlags()` 去除了标题栏,并使用 `setAttribute(Qt::WA_TranslucentBackground)` 设置透明背景。然后,在 `mousePressEvent()`、`mouseMoveEvent()` 和 `mouseReleaseEvent()` 函数中实现了移动窗口的功能。在 `resizeEvent()` 函数中,我们使用 `update()` 函数通知窗口重新绘制,以便在缩放窗口时更新窗口内容。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)