PyQt: how to handle event without inheritance

2024/9/22 12:44:39

How can I handle mouse event without a inheritance, the usecase can be described as follows:

Suppose that I wanna let the QLabel object to handel MouseMoveEvent, the way in the tutorial often goes in the way that we create a new class inherited from QLabel. But can I just use a lambda expression to handel the event without inheritance just like

ql = QLabel()
ql.mouseMoveEvent = lambda e : print e.x(), e.y()

So I do not need to write a whole class and just use simple lambda expression to implement some simple event.

Answer

The most flexible way to do this is to install an event filter that can receive events on behalf of the object:

from PyQt4 import QtGui, QtCoreclass Window(QtGui.QWidget):def __init__(self):QtGui.QWidget.__init__(self)self.label = QtGui.QLabel(self)self.label.setText('Hello World')self.label.setAlignment(QtCore.Qt.AlignCenter)self.label.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)self.label.setMouseTracking(True)self.label.installEventFilter(self)layout = QtGui.QVBoxLayout(self)layout.addWidget(self.label)def eventFilter(self, source, event):if (event.type() == QtCore.QEvent.MouseMove andsource is self.label):pos = event.pos()print('mouse move: (%d, %d)' % (pos.x(), pos.y()))return QtGui.QWidget.eventFilter(self, source, event)if __name__ == '__main__':import sysapp = QtGui.QApplication(sys.argv)window = Window()window.show()window.resize(200, 100)sys.exit(app.exec_())
https://en.xdnf.cn/q/71945.html

Related Q&A

DHT22 Sensor import Adafruit_DHT error

So Ive properly attached DHT22 Humidity Sensor to my BeagleBone Black Rev C. Im running OS Mavericks on my MacBook Pro and I followed the directions provided by Adafruit on how to use my DHT22 The webs…

Whats the purpose of package.egg-info folder?

Im developing a python package foo. My project structure looks like this:. ├── foo │ ├── foo │ │ ├── bar.py │ │ ├── foo.py │ │ ├── __init__.py │ ├── README.md …

Implement Causal CNN in Keras for multivariate time-series prediction

This question is a followup to my previous question here: Multi-feature causal CNN - Keras implementation, however, there are numerous things that are unclear to me that I think it warrants a new quest…

How to decode a numpy array of dtype=numpy.string_?

I need to decode, with Python 3, a string that was encoded the following way:>>> s = numpy.asarray(numpy.string_("hello\nworld")) >>> s array(bhello\nworld, dtype=|S11)I tri…

Cosine similarity of word2vec more than 1

I used a word2vec algorithm of spark to compute documents vector of a text. I then used the findSynonyms function of the model object to get synonyms of few words. I see something like this: w2vmodel.f…

Handling empty case with tuple filtering and unpacking

I have a situation with some parallel lists that need to be filtered based on the values in one of the lists. Sometimes I write something like this to filter them:lista = [1, 2, 3] listb = [7, 8, 9] f…

pip3 install pyautogui fails with error code 1 Mac OS

I tried installing the autogui python extension:pip3 install pyautoguiAnd this installation attempt results in the following error message:Collecting pyautoguiUsing cached PyAutoGUI-0.9.33.zipComplete …

BERT get sentence embedding

I am replicating code from this page. I have downloaded the BERT model to my local system and getting sentence embedding. I have around 500,000 sentences for which I need sentence embedding and it is t…

Python Subversion wrapper library

In Subversions documentation theres an example of using Subversion from Python#!/usr/bin/python import svn.fs, svn.core, svn.reposdef crawl_filesystem_dir(root, directory):"""Recursively…

How to convert a selenium webelement to string variable in python

from selenium import webdriver from time import sleep from selenium.common.exceptions import NoSuchAttributeException from selenium.common.exceptions import NoSuchElementException from selenium.webdriv…