[Pyqt5] 드래그를 하여, 윈도우창 이동하기 (How to move window when dragging frame) [7]

2021. 6. 28. 08:37GUI Programming/PyQT5 (GUI Programming)

반응형

[Pyqt5]

이번 포스팅은 타이틀바를 사용하지않고 마우스 드래그만을 통해 창을 옮기는 방법에 대해 포스팅 하겠습니다.

 

보통 이 방법은 윈도우를 깔끔하게 디자인 하기 위해 타이틀바를 제거하고,

타이틀 바를 이용하지않고 윈도우를 움직이게 하기 위해 사용됩니다.


(스포) [왼쪽 - 타이틀바 이용, 오른쪽 - 드래그 이용]

 


우선 메인 윈도우를 생성 해줍니다.

타이틀바는 제거 해줍니다.

그리고 해당 방법을 이용하면 윈도우 창을 종료하는 방법이 없기 때문에

윈도우 창을 종료하게 해주는 버튼을 추가해줍니다.

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
from PyQt5.QtCore import Qt,QRect
from PyQt5.QtGui import QMouseEvent, QCursor, QPixmap
import sys

class MainWiondw(QWidget):
	def __init__(self):
		super().__init__()

		self.width = 526
		self.height = 459

		self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
		self.resize(self.width, self.height)
		self.centralwidget = QWidget(self)
		self.centralwidget.setObjectName("centralwidget")

		self.label = QLabel(self.centralwidget)
		self.label.setGeometry(QRect(0, 0, self.width, self.height))
		self.label.setObjectName("label")
		self.label.setPixmap(QPixmap("GCVPv.png")) #image path

		self.Exit_button = QPushButton('X',self.centralwidget,)
		self.Exit_button.setGeometry(QRect(self.width-30,10,20,20))
		self.Exit_button.setStyleSheet("background-color : rgba(255, 255, 255, 200)")
		self.Exit_button.setObjectName('Exit_button')
		self.Exit_button.clicked.connect(self.Exit_button_click)

마우스 이벤트를 활용해주시면

마우스를 클릭했을때 윈도우를 움직일 수 있게됩니다.

 

(코드는 클래스안에 넣으셔야 합니다.)

# MOUSE Click drag EVENT function
def mousePressEvent(self, event):
    if event.button()==Qt.LeftButton:
        self.m_flag=True
        self.m_Position=event.globalPos()-self.pos() #Get the position of the mouse relative to the window
        event.accept()
        self.setCursor(QCursor(Qt.OpenHandCursor))  #Change mouse icon

def mouseMoveEvent(self, QMouseEvent):
    if Qt.LeftButton and self.m_flag:  
        self.move(QMouseEvent.globalPos()-self.m_Position)#Change window position
        QMouseEvent.accept()

def mouseReleaseEvent(self, QMouseEvent):
    self.m_flag=False
    self.setCursor(QCursor(Qt.ArrowCursor))

마지막으로 종료 버튼을 눌렀을 때, 종료가 되도록 함수를 만들어줍니다.

# Exit Button click event
def Exit_button_click(self,MainWindow):
    sys.exit(app.exec_())

[결과]

 

이상 포스팅을 마치도록하겠습니다.

 

[완성된 코드]

https://github.com/Mr-DooSun/pyqt5-gui/tree/master/ex5_mouse_event

 

Mr-DooSun/pyqt5-gui

Contribute to Mr-DooSun/pyqt5-gui development by creating an account on GitHub.

github.com

 

반응형