# coding: utf-8
import sys
import traceback

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class Main(QDialog):
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
            # self.init_slot()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.setMouseTracking(True)
            self.setWindowFlags(Qt.FramelessWindowHint)
            # self.setWindowFlags(Qt.CustomizeWindowHint)
            self.resize(480, 240)

            self.label_title = QLabel("无边框demo", self)
            self.label_title.setFixedHeight(30)
            self.label_title.setStyleSheet("background-color: black; color: white;")

            self.widget = QWidget(self)

            layout = QVBoxLayout(self)
            layout.addWidget(self.label_title)
            layout.addWidget(self.widget)

            layout.setSpacing(0)
            layout.setContentsMargins(0, 0, 0, 0)
            self.setLayout(layout)
        except:
            traceback.print_exc()

    def resizeEvent(self, QResizeEvent):
        super(Main, self).resizeEvent(QResizeEvent)

    def mousePressEvent(self, QMouseEvent):
        try:
            # 当前坐标
            self.startMovePos = QMouseEvent.globalPos()
            x = self.startMovePos.x()
            y = self.startMovePos.y()

            # 允许范围
            x0 = self.pos().x()
            y0 = self.pos().y()

            x1 = x0 + self.label_title.width()
            y1 = y0 + self.label_title.height()

            if x0 < x < x1 and y0 < y < y1:
                self.isPressed = True
            else:
                self.isPressed = False
        except:
            traceback.print_exc()

    def mouseMoveEvent(self, QMouseEvent):
        try:
            if self.isPressed:
                # 起点
                x = self.pos().x()
                y = self.pos().y()

                # 偏差
                x0 = self.startMovePos.x()
                y0 = self.startMovePos.y()

                self.endMovePos = QMouseEvent.globalPos()
                x1 = self.endMovePos.x()
                y1 = self.endMovePos.y()

                x_delta = x1 - x0
                y_delta = y1 - y0

                self.startMovePos = QMouseEvent.globalPos()
                self.move(x + x_delta, y + y_delta)
        except:
            traceback.print_exc()

    def mouseReleaseEvent(self, QMouseEvent):
        try:
            self.isPressed = False
        except:
            traceback.print_exc()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
