Skip to content

[PyQt5] Hide the title bar and use mouse to move the interface

Last Updated on 2021-03-04 by Clay


The Introduction

When we using PyQt5 tool to design the program graphical interface, sometimes maybe we want to hide the title bar to make our interface beauty:

This is a countdown timer demo

After hiding the title bar:

Is it more suitable?

But today after I hiding the title bar, I suddenly thought of another problem: HOW DO I MOVE THIS APP?

Before hiding the title bar, we all dragging it with the mouse by pressing and holding the title bar. But there is no title bar not.

After studying for a while, I finally found a good method-just overwrite the three methods of:

  • mousePressEvent()
  • mouseMoveEvent()
  • mouseReleaseEvent()

mousePressEvent()

def mousePressEvent(self, event):
    if event.button() == Qt.LeftButton:
        self.moveFlag = True
        self.movePosition = event.globalPos() - self.pos()
        self.setCursor(QCursor(Qt.OpenHandCursor))
        event.accept()


This method was originally the method of the interface we inherited and now we need to rewrite this method.

When we judge the mouse to press the left button, moveFlag is True, and let the system automatically calculate the difference between the "mouse position" and the "interface coordinate position", which is the offset from mouse position to the interface position.

By the way, the setCursor() method just change the mouse icon.


mouseMoveEvent()

The offset has just been calculated, let's see how to move the interface.

def mouseMoveEvent(self, event):
    if Qt.LeftButton and self.moveFlag:
        self.move(event.globalPos() - self.movePosition)
        event.accept()


If our variable moveFlag is True, so in the same time if our left mouse click, we can move our interface by move() method.

The two method have worked like the above picture.

  • movePressEvent() record the offset
  • mouseMoveEvent() move the interface

And then we need to rewrite the third method, to stop our move action.


mouseReleaseEvent()

def mouseReleaseEvent(self, event):
    self.moveFlag = False
    self.setCursor(Qt.CrossCursor)

If our mouse release, we need to set moveFlag to False and the interface will stop moving.

And use setCursor() again to change the mouse icon back.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version