和之前用c++qt写的一样逻辑:
https://blog.csdn.net/qq_34974229/article/details/134651103?spm=1001.2014.3001.5502
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QMouseEvent
from login_form import Ui_Frame # 界面1
from widget import Ui_Widget # 界面2
class LoginWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_Frame()
self.ui.setupUi(self)
# 设置该窗口是一个顶级窗口并去除窗口的框架和标题栏,使窗口无边框
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
# 设置窗口的背景为半透明
self.setAttribute(Qt.WA_TranslucentBackground)
# 设置窗口在关闭时自动销毁(delete)
self.setAttribute(Qt.WA_DeleteOnClose)
# 设置其他窗口无法与之交互,直到该模态窗口关闭
self.setWindowModality(Qt.ApplicationModal)
self.m_bPressed = False
self.m_point = QPoint()
def mousePressEvent(self, event: QMouseEvent):
if event.button() == Qt.LeftButton:
self.m_bPressed = True
self.m_point = event.globalPos() - self.pos()
def mouseMoveEvent(self, event: QMouseEvent):
if self.m_bPressed:
self.move(event.globalPos() - self.m_point)
def mouseReleaseEvent(self, event: QMouseEvent):
self.m_bPressed = False
def closeEvent(self, event):
# 在关闭窗口时销毁(delete)该窗口
self.deleteLater()
# 调用父类的 closeEvent 方法,以确保窗口的正常关闭
super().closeEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = LoginWindow()
window.show()
sys.exit(app.exec_())
限制只能self.widget中按压移动
class MainUnit(QWidget, MainWidgetUI):
def __init__(self, ):
super(MainUnit, self).__init__()
self.setupUi(self)
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_DeleteOnClose)
self.offset = QPoint()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
# 检查鼠标点击是否在self.widget内
if self.widget.geometry().contains(event.pos()):
self.offset = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
# 检查鼠标是否在self.widget内按下并移动
if self.widget.geometry().contains(event.pos()):
self.move(event.globalPos() - self.offset)
event.accept()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
event.accept()