프로그래밍 언어/Python

[PyQt] 마우스 클릭 시 사용 버튼 구하기

sujo 2022. 10. 2. 10:05

[PyQt] 마우스 클릭 시 사용 버튼 구하기

 

개요

  • 마우스 클릭 시 왼쪽/휠/오른쪽 중 어느 쪽을 눌렀는지 구한다.
  • "mousePressEvent" 사용
    • Qt.LeftButton : 왼쪽 클릭
    • Qt.MidButton : 휠 클릭
    • Qt.RightButton : 오른쪽 클릭
  • 아래는 사용된 ui 파일이다.
더보기
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>250</x>
      <y>230</y>
      <width>281</width>
      <height>21</height>
     </rect>
    </property>
    <property name="text">
     <string>TextLabel</string>
    </property>
    <property name="alignment">
     <set>Qt::AlignCenter</set>
    </property>
   </widget>
   <widget class="QLabel" name="title">
    <property name="geometry">
     <rect>
      <x>360</x>
      <y>180</y>
      <width>71</width>
      <height>21</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <pointsize>12</pointsize>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
    <property name="text">
     <string>Mouse</string>
    </property>
    <property name="alignment">
     <set>Qt::AlignCenter</set>
    </property>
   </widget>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>



 

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
 
class window_class(QMainWindow):
    def __init__(self):
        from PyQt5.uic import loadUi
        super(window_class, self).__init__()
        loadUi('../../ui/mouse.ui'self)
 
    def mousePressEvent(self, e):
        if e.button() == Qt.LeftButton:
            click = 'Left Mouse'
        if e.button() == Qt.MidButton:
            click = 'Middle Mouse'
        if e.button() == Qt.RightButton:
            click = 'Right Mouse'
        self.label.setText(click)
 
import sys
app = QApplication(sys.argv)
window = window_class()
window.show()
app.exec()
cs

 

 

결과 화면

: 왼쪽 마우스 클릭

 

: 휠 클릭

 

: 오른쪽 마우스 클릭