0
votes

I put a subclass (QDicomLabel_contrast) inherited from QLabel in a QWidget, and the mouse move event in QDicomLabel_contrast can not be call back. The code is:

from PyQt5.QtWidgets import *
import sys

class QDicomLabel_contrast(QLabel):
    def __init__(self,parent=None):
        super(QDicomLabel_contrast,self).__init__(parent)
        self.setStyleSheet("background-color:black")
        self.setMouseTracking(True)

    def mouseMoveEvent(self, QMouseEvent):
        pos = QMouseEvent.pos()
        print(pos.x(), pos.y())


if __name__ == '__main__':

    class MainWindow(QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)

            self.resize(500,500)
            self.imagelabel = QDicomLabel_contrast()
            self.imagelabel.resize(300,300)
            self.imagelabel.setParent(self)
            #self.imagelabel.show()

            self.imagelabel.setGeometry(10, 20, 300,300)

            widget = QWidget()
            self.setCentralWidget(widget)
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

the mouseMoveEvent in QDicomLabel_contrast can not be called. However, if I use self.imagelabel.show() instead of self.imagelabel.setParent(self), the mouseMoveEvent can be called, just like: from PyQt5.QtWidgets import * import sys

class QDicomLabel_contrast(QLabel):
    def __init__(self,parent=None):
        super(QDicomLabel_contrast,self).__init__(parent)
        self.setStyleSheet("background-color:black")
        self.setMouseTracking(True)

    def mouseMoveEvent(self, QMouseEvent):
        pos = QMouseEvent.pos()
        print(pos.x(), pos.y())


if __name__ == '__main__':

    class MainWindow(QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)

            self.resize(500,500)
            self.imagelabel = QDicomLabel_contrast()
            self.imagelabel.resize(300,300)
            #self.imagelabel.setParent(self)
            self.imagelabel.show()

            self.imagelabel.setGeometry(10, 20, 300,300)

            widget = QWidget()
            self.setCentralWidget(widget)
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()
1

1 Answers

0
votes

I has found the solution.

The reason why mouse move function can not be called is that the mouse move event will be passed to QWidget. So, if I indicate the parent to QWidget, the problem will be ok: self.imagelabel.setParent(widget).