PyQt5可拖动无框窗口

我find了一个例子来设置无框窗口的边界,但不能拖动。 我怎样才能使无框窗口可拖动? 特别是如果我能看到一个例子,它会很棒。 这里是我的示例代码(通常代码更长,这就是为什么有很多库只是不介意);

from PyQt5.QtWidgets import (QMessageBox,QApplication, QWidget, QToolTip, QPushButton, QDesktopWidget, QMainWindow, QAction, qApp, QToolBar, QVBoxLayout, QComboBox,QLabel,QLineEdit,QGridLayout,QMenuBar,QMenu,QStatusBar, QTextEdit,QDialog,QFrame,QProgressBar ) from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtGui import QIcon,QFont,QPixmap,QPalette from PyQt5.QtCore import QCoreApplication, Qt,QBasicTimer import sys class cssden(QMainWindow): def __init__(self): super().__init__() self.mwidget = QMainWindow(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #size self.setFixedSize(320, 450) self.center #label self.lbl = QLabel(self) self.lbl.setText("test") self.lbl.setStyleSheet("background-color: rgb(0,0,0);" "border: 1px solid red;" "color: rgb(255,255,255);" "font: bold italic 20pt 'Times New Roman';") self.lbl.setGeometry(5,5,60,40) self.show() #center def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) app = QApplication(sys.argv) app.setStyleSheet("QMainWindow{background-color: darkgray;border: 1px solid black}") ex = cssden() sys.exit(app.exec_()) 

Solutions Collecting From Web of "PyQt5可拖动无框窗口"

你需要自己处理鼠标事件。

  • 我们将需要在mousePressEvent上添加一个事件,这将保持我们上次点击窗口的地方
  • 然后,我们将添加一个mouseMoveEvent ,它将计算最后点击的点和当前鼠标位置之间的距离。 我们将根据这个距离移动窗口。

这是固定的代码:

 from PyQt5.QtWidgets import (QMessageBox,QApplication, QWidget, QToolTip, QPushButton, QDesktopWidget, QMainWindow, QAction, qApp, QToolBar, QVBoxLayout, QComboBox,QLabel,QLineEdit,QGridLayout,QMenuBar,QMenu,QStatusBar, QTextEdit,QDialog,QFrame,QProgressBar ) from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtGui import QIcon,QFont,QPixmap,QPalette from PyQt5.QtCore import QCoreApplication, Qt,QBasicTimer, QPoint import sys class cssden(QMainWindow): def __init__(self): super().__init__() self.mwidget = QMainWindow(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #size self.setFixedSize(320, 450) self.center() #label self.lbl = QLabel(self) self.lbl.setText("test") self.lbl.setStyleSheet("background-color: rgb(0,0,0);" "border: 1px solid red;" "color: rgb(255,255,255);" "font: bold italic 20pt 'Times New Roman';") self.lbl.setGeometry(5,5,60,40) self.oldPos = self.pos() self.show() #center def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QPoint (event.globalPos() - self.oldPos) #print(delta) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos() app = QApplication(sys.argv) app.setStyleSheet("QMainWindow{background-color: darkgray;border: 1px solid black}") ex = cssden() sys.exit(app.exec_())