PDA

View Full Version : how to setup simple mouse event



Nfrancisj
29th March 2016, 07:29
Hello,
Continuing on my studying of Qt, Id like to learn about MouseEvents and Events in general.

for testing i have a super basic window with just a single label on it.
I've turned on mouse tracking as per the docs instruction, but i dont know how to capture the signals. i dont see onMouseOver / Hover.

what I am trying to do:

when my mouse is over the label, it executes a function 'changedText' that changes the text to 'yay'

...
self.myLabel.setMouseTracking(True)
self.myLabel.setText('put mouse is over the label')


#function to call
def changeText():
self.myLabel.setText(' YaY!')


Cheers!

anda_skoa
29th March 2016, 09:08
QWidget::enterEvent(), QWidget::leaveEvent().

Cheers,
_

Narada
4th April 2016, 04:24
I found this presentation really useful.

http://www.comp.nus.edu.sg/~cs3249/lecture/event%20processing.pdf

Nfrancisj
17th April 2016, 22:31
Thanks!

For anyone that's interested, I was able to implement enter & leave event by subclassing the widget like this:


from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
import os,sys


class Main(QtGui.QWidget):

def __init__(self, parent=None):
super(Main, self).__init__(parent)

layout = QtGui.QVBoxLayout(self) # layout of main widget

button = HoverButton(self)
button.setIconSize(QtCore.QSize(200,200))

layout.addWidget(button) # set your button to the widgets layout
# this will size the button nicely


class HoverButton(QtGui.QToolButton):

def __init__(self, parent=None):
super(HoverButton, self).__init__(parent)
self.setMouseTracking(True)

def enterEvent(self,event):
print("Enter")
self.setStyleSheet("background-color:#45b545;")

def leaveEvent(self,event):
self.setStyleSheet("background-color:yellow;")
print("Leave")

app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())