진짜 겁나 간단하다.

 

https://wiki.python.org/moin/PyQt/Making%20non-clickable%20widgets%20clickable

 

PyQt/Making non-clickable widgets clickable - Python Wiki

On the #pyqt channel on Freenode, xh asked if it was possible to make QLabel objects clickable without subclassing. There are two ways to do this: Use event filters. Assign new methods to the labels. These are shown below. Event filters The following examp

wiki.python.org

 

관련 문서는 바로 위 링크에 있다.

 

def clickable(widget):

    class Filter(QObject):
    
        clicked = pyqtSignal()	#pyside2 사용자는 pyqtSignal() -> Signal()로 변경
        
        def eventFilter(self, obj, event):
        
            if obj == widget:
                if event.type() == QEvent.MouseButtonRelease:
                    if obj.rect().contains(event.pos()):
                        self.clicked.emit()
                        # The developer can opt for .emit(obj) to get the object within the slot.
                        return True
            
            return False
    
    filter = Filter(widget)
    widget.installEventFilter(filter)
    return filter.clicked

위의 코드를 내가 사용하고 싶은 곳에 복붙을 한다.

 

clickable(label1).connect(self.showText1)

clickable('내가 이벤트를 발생시키고 싶은 객체').connect('발생시킬 이벤트 함수')

 

이런 식으로 작성해주면 아주 잘 작동한다.

-> 단순히 라벨뿐만 아니라 프레임, widget 등 QObject 객체라면 모두 사용이 가능하다.

 

connect 함수에서 파라미터를 보내고 싶으면 lambda 함수를 사용하면 되고 ㅎㅎ

 

위의 코드를 보면 clicked라는 이름의 시그널을 생성하고, 이벤트 중 마우스 클릭 이벤트가 발생하면, 해당 이벤트 발생 위치를 분석해서 그 위치가 오브젝트의 사각형 안에 들어갈 경우 click signal을 emit해주는 것.

 

한마디로 QEvent.mousebuttonRelease() 함수만 다른걸로 바꿔주면 여러가지 이벤트를 다양하게 생성할 수 있다는 의미이다.

 

개 꿀

 

 

+ Recent posts