使用pyqt4创建可拖动窗口
这是一个简单的问题:我正在使用pyqt4来创建一个简单的窗口。这里是代码,我把整个代码贴出来,这样更容易解释。
from PyQt4 import QtGui, QtCore, Qt
import time
import math
class FenixGui(QtGui.QWidget):
def __init__(self):
super(FenixGui, self).__init__()
# setting layout type
hboxlayout = QtGui.QHBoxLayout(self)
self.setLayout(hboxlayout)
# hiding title bar
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# setting window size and position
self.setGeometry(200, 200, 862, 560)
self.setAttribute(Qt.Qt.WA_TranslucentBackground)
self.setAutoFillBackground(False)
# creating background window label
backgroundpixmap = QtGui.QPixmap("fenixbackground.png")
self.background = QtGui.QLabel(self)
self.background.setPixmap(backgroundpixmap)
self.background.setGeometry(0, 0, 862, 560)
# fenix logo
logopixmap = QtGui.QPixmap("fenixlogo.png")
self.logo = QtGui.QLabel(self)
self.logo.setPixmap(logopixmap)
self.logo.setGeometry(100, 100, 400, 150)
def main():
app = QtGui.QApplication([])
exm = FenixGui()
exm.show()
app.exec_()
if __name__ == '__main__':
main()
现在,你可以看到我在窗口里放了一个背景标签。我希望通过拖动这个标签来移动整个窗口。我的意思是:你点击这个标签,拖动它,然后整个窗口就跟着移动。这样可以实现吗?我也接受一些不太优雅的方法,因为你可以看到我把标题栏隐藏了,如果不通过这个背景标签来实现拖动,就无法移动窗口。
希望我能清楚地解释我的问题。非常感谢!!
Matteo Monti
1 个回答
5
你可以重写 mousePressEvent() 和 mouseMoveEvent() 这两个方法,来获取鼠标光标的位置,并把你的窗口小部件移动到那个位置。mousePressEvent
方法会告诉你鼠标光标到你的小部件左上角的偏移量,然后你就可以计算出左上角的新位置应该在哪里。你可以把这些方法添加到你的 FenixGui
类里面。
def mousePressEvent(self, event):
self.offset = event.pos()
def mouseMoveEvent(self, event):
x=event.globalX()
y=event.globalY()
x_w = self.offset.x()
y_w = self.offset.y()
self.move(x-x_w, y-y_w)