= Making non-clickable widgets clickable = 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: 1. Use event filters. 2. Assign new methods to the labels. These are shown below. == Event filters == The following example code shows how to use event filters to do this. It uses one filter object per label, which is created when the `clickable()` function is called with the widget that is to be click-enabled. The function returns a `clicked()` signal that actually belongs to the filter object. The caller can connect this signal to a suitable callable object. {{{ #!python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def clickable(widget): class Filter(QObject): clicked = pyqtSignal() 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 class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) label1 = QLabel(self.tr("Hello world!")) label2 = QLabel(self.tr("ABC DEF GHI")) label3 = QLabel(self.tr("Hello PyQt!")) clickable(label1).connect(self.showText1) clickable(label2).connect(self.showText2) clickable(label3).connect(self.showText3) layout = QHBoxLayout(self) layout.addWidget(label1) layout.addWidget(label2) layout.addWidget(label3) def showText1(self): print "Label 1 clicked" def showText2(self): print "Label 2 clicked" def showText3(self): print "Label 3 clicked" if __name__ == "__main__": app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) }}} == Assigning new methods == As `xh` pointed out, it should be possible to assign new event handler methods to instances of QLabel, and this should work as long as the labels were created in Python: {{{ #!python import sys from PyQt4.QtGui import * class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) label1 = QLabel(self.tr("Hello world!")) label2 = QLabel(self.tr("ABC DEF GHI")) label3 = QLabel(self.tr("Hello PyQt!")) label1.mouseReleaseEvent = self.showText1 label2.mouseReleaseEvent = self.showText2 label3.mouseReleaseEvent = self.showText3 layout = QHBoxLayout(self) layout.addWidget(label1) layout.addWidget(label2) layout.addWidget(label3) def showText1(self, event): print "Label 1 clicked" def showText2(self, event): print "Label 2 clicked" def showText3(self, event): print "Label 3 clicked" if __name__ == "__main__": app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) }}}