Home > OS >  PyQt Mouse Event doesn't work on my QLabel with CSS
PyQt Mouse Event doesn't work on my QLabel with CSS

Time:10-15

I use a specific font when programming. But the font has a narrow line gap, so I use CSS to define the line spacing separately. But this is where the problem arises. Mouse Event is not working. What's the reason and what should I do?

Here is my code:

import sys
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.label = QLabel(self)
        self.label.resize(200, 50)
        self.label.setStyleSheet("border: 1px solid black;")

        text = "Test mouse events on here"
        self.label.setText("<p style='line-height:1.15'>{}</p>".format(text))

    def mouseReleaseEvent(self, e):
        if e.button() == QtCore.Qt.LeftButton:
            print("Left")

        if e.button() == QtCore.Qt.RightButton:
            print("Right")

        if e.button() == 8: 
            print("Left side")

        if e.button() == 16: 
            print("Right side")

App = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec())

CodePudding user response:

The problem is caused because when you put rich text the QLabel consumes the mouse events preventing it from being propagated to the parents. A possible solution is to activate the attribute Qt::WA_TransparentForMouseEvents:

self.label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True)
  • Related