The MouseEvent of Qlabel doesn't work, after an advanced click on the label.
-
I' m using PyQt5 and QtDesigner on Ubuntu platform to develop an application and confronted with a problem on Qlabel.MouseEvent. To illustrate the problem, I make a simple UI example ( Fig. 1) in QtDesigner and then convert the .ui to python file for further development.
Fig.1 Making an simple example in QtDesigner.The .ui file is here and the modified code is below, where ui_test is generated by pyuic5 command:
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import QEvent from ui_test import Ui_MainWindow class MyMainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MyMainWindow, self).__init__() self.setupUi(self) # Connect slots: self.pushButton.clicked.connect(self.btn_callback) def pressed_callback(self, event): # Just print the pixel location of cursor in the textLabel self.textLabel.setText("(px: " + str(event.pos().x()) + " , " + "py: " + str(event.pos().y()) + ")") # print((event.pos().x(), event.pos().y())) def btn_callback(self): # Push to enable print the pixel loction of mouse cursor on the mainLabel self.mainLabel.mousePressEvent = self.pressed_callback if __name__ == "__main__": app = QApplication(sys.argv) win = MyMainWindow() win.show() sys.exit(app.exec_())
I can click the button to enable print the pixel loction of mouse cursor when I press the mainLabel arrea (Fig.2). The app works well if I press the button at first. But, the self.mainLabel.mousePressEvent won't work at all if I do a click on the mainLabel before I click the button. Then nothing will happen if I press the mainLabel. How can I fix it?
-
Hi and welcome to devnet,
@ZhongQL said in The MouseEvent of Qlabel doesn't work, after an advanced click on the label.:
def btn_callback(self):
# Push to enable print the pixel loction of mouse cursor on the mainLabel
self.mainLabel.mousePressEvent = self.pressed_callbackWhy are you replacing mousePressEvent with pressed_calldback ? You are nuking the original functionality by doing that.
-
What exactly do you want to happen when clicking on that QLabel ?
The proper way is to create a subclass of QLabel and re-implement mousePressEvent however you can do things a bit differently since you are using Python.