带有pyqt4的可拖动窗口 [英] Draggable window with pyqt4
问题描述
一个简单的问题:我正在使用pyqt4渲染一个简单的窗口。这是代码,我将整个内容发布了起来,以便于解释。
just a simple question: I'm using pyqt4 to render a simple window. Here's the code, I post the whole thing so it easier to explain.
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()
现在,您看到我在窗口中放置了一个背景标签。我希望可以通过拖动此标签在屏幕周围拖动窗口。我的意思是:单击标签,然后拖动标签,整个窗口就会出现在屏幕周围。这可能吗?我也接受非优雅的方式,因为如您所见,我隐藏了标题栏,因此,如果我不能通过背景标签将其拖动,则不可能拖动窗口。
Now, you see that I put a background label in my window. I would like that the window could be dragged around the screen by dragging this label. I mean: you click on the label, you drag the label, and the whole window comes around the screen. Is this possible? I accept non-elegant ways as well, because as you can see I hid the title bar so it would be impossible to drag the window if I don't make it draggable via the background label.
希望我能正确解释我的问题
非常感谢!!
Hope I explained my problem properly Thank you very much!!
Matteo Monti
Matteo Monti
推荐答案
您可以覆盖 mousePressEvent()和 mouseMoveEvent ()获取鼠标光标的位置并将小部件移至该位置。 mousePressEvent
将为您提供从光标位置到窗口小部件左上角的偏移量,然后您可以计算左上角的新位置。您可以将这些方法添加到您的 FenixGui
类中。
You can override mousePressEvent() and mouseMoveEvent() to get the location of the mouse cursor and move your widget to that location. mousePressEvent
will give you the offset from the cursor position to the top left corner of your widget, and then you can calculate what the new position of the top left corner should be. You can add these methods to your FenixGui
class.
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)
这篇关于带有pyqt4的可拖动窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!