Qt 圆角矩形+鼠标左键拖动窗口

 1 #ifndef MAINWINDOW_H
 2 #define MAINWINDOW_H
 3 
 4 #include <QMainWindow>
 5 
 6 namespace Ui {
 7 class MainWindow;
 8 }
 9 
10 class MainWindow : public QMainWindow
11 {
12     Q_OBJECT
13 
14 public:
15     explicit MainWindow(QWidget *parent = 0);
16     ~MainWindow();
17 
18 protected:
19     void paintEvent(QPaintEvent *event);
20     void mousePressEvent(QMouseEvent *event);
21     void mouseMoveEvent(QMouseEvent *event);
22     void mouseReleaseEvent(QMouseEvent *event);
23 
24 private:
25     Ui::MainWindow *ui;
26 
27     QPoint m_pos;
28     bool m_drag;
29 };
30 
31 #endif // MAINWINDOW_H
 1 #include "mainwindow.h"
 2 #include "ui_mainwindow.h"
 3 
 4 #include <QPainter>
 5 #include <QBitmap>
 6 #include <QMouseEvent>
 7 
 8 MainWindow::MainWindow(QWidget *parent)
 9     : QMainWindow(parent),
10       ui(new Ui::MainWindow)
11 {
12     ui->setupUi(this);
13 
14     ui->menuBar->close();
15     ui->mainToolBar->close();
16     ui->statusBar->close();
17 
18     setFixedSize(400, 300);
19     setWindowFlags(Qt::FramelessWindowHint);
20 
21     m_drag = false;
22 }
23 
24 MainWindow::~MainWindow()
25 {
26     delete ui;
27 }
28 
29 void MainWindow::paintEvent(QPaintEvent *event)
30 {
31     Q_UNUSED(event);
32     QBitmap bitmap(this->size());
33     QPainter painter(&bitmap);
34     painter.fillRect(this->rect(), Qt::white);
35     painter.setBrush(QColor(0, 0, 0));
36     painter.setRenderHint(QPainter::Antialiasing);
37     painter.setPen(QPen(Qt::blue, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
38     painter.drawRoundedRect(this->rect(), 4, 4);
39     this->setMask(bitmap);
40 }
41 
42 void MainWindow::mousePressEvent(QMouseEvent *event)
43 {
44     if (Qt::LeftButton == event->button()) {
45         m_drag = true;
46         m_pos = event->pos();
47     }
48 }
49 
50 void MainWindow::mouseMoveEvent(QMouseEvent *event)
51 {
52     Q_UNUSED(event);
53 
54     if (m_drag) {
55         this->move(event->globalPos() - m_pos);
56     }
57 }
58 
59 void MainWindow::mouseReleaseEvent(QMouseEvent *event)
60 {
61     Q_UNUSED(event);
62     m_drag = false;
63 }

 

posted @ 2016-04-19 16:50  jasaiq  阅读(1066)  评论(0编辑  收藏  举报