Draggable window with pyqt4

2020-06-06 04:01发布

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

1条回答
再贱就再见
2楼-- · 2020-06-06 04:57

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)
查看更多
登录 后发表回答