PyQt 鼠标事件在我的 QLabel 上使用 CSS 不起作用



我在编程时使用了特定的字体。但是字体的行间距很窄,所以我使用CSS单独定义行间距。但问题就出在这里。鼠标事件不工作。原因是什么?我该怎么做?

下面是我的代码:
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())

出现这个问题是因为当您放置富文本时,QLabel会消耗鼠标事件,从而阻止它传播到父类。一个可能的解决方案是激活属性Qt::WA_TransparentForMouseEvents:

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

最新更新