Draggable window with pyqt4

风流意气都作罢 提交于 2020-01-01 03:49:12

问题


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:


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)


来源:https://stackoverflow.com/questions/7138773/draggable-window-with-pyqt4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!