Make QLabel clickable

I do not understand why you pass QMouseEvent to the parent constructor, you must pass the parent attribute as shown below:

class QLabel_alterada(QLabel):
    clicked=pyqtSignal()

    def mousePressEvent(self, ev):
        self.clicked.emit()

To avoid having problems with imports we can directly promote the widget as shown below:

We place a QLabel and right click and choose Promote to ...:

enter image description here

We get the following dialog and place the QLABEL2.h in header file and QLabel_changed in Promoted class Name, then press Add and Promote

enter image description here

Then we generate the .ui file with the help of pyuic. Obtaining the following structure:

├── main.py
├── QLABEL2.py
└── Ui_main.ui

Obtaining the following structure:

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.clicked.connect(self.dosomestuff) 

    def dosomestuff(self):
        print("click")


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Leave a Comment