I have a Qlabel filled with QPixmap and I want to start a process/function once this label clicked. I had extended QLabel class as follows:
from PyQt5.QtCore
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 __init__(self, parent=None):
QLabel.__init__(self, parent)
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 ...
:
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
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_())
class ClickableLabel(QtWidgets.QLabel):
def __init__(self, whenClicked, parent=None):
QtWidgets.QLabel.__init__(self, parent)
self._whenClicked = whenClicked
def mouseReleaseEvent(self, event):
self._whenClicked(event)
and then:
my_label = ClickableLabel(self.my_label_clicked)
...
def my_label_clicked(self, event):
button = event.button()
modifiers = event.modifiers()
if modifiers == Qt.NoModifier and button == Qt.LeftButton:
logger.debug('my_label_clicked: hooray!')
return
LOGGER.debug('my_label_clicked: unhandled %r', event)