Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
The MouseEvent of Qlabel doesn't work, after an advanced click on the label.
ZhongQL last edited by ZhongQL
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,
# Push to enable print the pixel loction of mouse cursor on the mainLabel
self.mainLabel.mousePressEvent = self.pressed_callback
Why are you replacing mousePressEvent with pressed_calldback ? You are nuking the original functionality by doing that.
ZhongQL last edited by
@SGaist I want to change the reaction of MouseEvent by pressing a button, what' s the right way to do that?
ZhongQL last edited by
@SGaist By the way, how should I define the MouseEvent function of a label generated by pyuic?
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.