Q 标签无法触发鼠标释放事件



我有一个父QLabel,并创建一个子QLabel来显示一些文本。当我单击子 QLabel 时,父 QLabel 上的 mousePressEvent 是正常的,但无法触发 mouseReleaseEvent。代码为:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyLabel(QLabel):
    def __init__(self):
        super(MyLabel, self).__init__()
        self.label = QLabel('hello<br/> world', self)
        self.label.adjustSize()
        self.label.setStyleSheet(
            "background-color: {};".format(QColor(255, 0, 0).name())
        )
        self.label.move(QPoint(50, 50))
        self.label.setFrameShape(QFrame.NoFrame)
    def mousePressEvent(self, QMouseEvent):
        super(MyLabel, self).mousePressEvent(QMouseEvent)
        print('press')
    def mouseReleaseEvent(self, QMouseEvent):
        super(MyLabel, self).mouseReleaseEvent(QMouseEvent)
        print('release')
class Window(QLabel):
    def __init__(self):
        super(Window, self).__init__()
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.label = MyLabel()
        self.label.setFrameShape(QFrame.Box)
        self.label.setStyleSheet("border-width: 2px;border-style: solid;border-color: rgb(0, 255, 0);")
        self.layout.addWidget(self.label)
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

我发现原因是子QLabel中的文本。如果我将文本显示为"hello world"而不是"hello<.br/> world",则当我单击"hello world"QLabel 时,鼠标释放信号正常。那么,如果我需要显示"你好<.br/>世界",如何修复此错误?

在mousePressEvent的情况下,事件从父级传递到子项,如果父项接受子项,则不会传递该子项,但默认情况下,父项会

忽略它,因为子子使用它的内容,但与mouseReleaseEvent不同,儿子使用事件,因此不会通知父项。

如果您想更好地了解鼠标事件的概念,请阅读以下文章:

  • 鼠标事件传播。

在这种情况下,还有另一种选择可以避免禁用 Korev @Romha指示的小部件,即激活标志 Qt::WA_TransparentForMouseEvents:

self.label = QLabel('hello<br/> world', self)
self.label.setAttribute(Qt.WA_TransparentForMouseEvents)

这将使 QLabel 下方的小部件接收鼠标事件,就好像 QLabel 不存在一样。

当您按下 hello world 标签上方的鼠标按钮时,MyLabel会将事件广播给其子级。

因此,hello world标签将是最终的接收者。一旦它收到新闻发布事件,它将自动接收发布事件。

如果要处理 MyLabel 中的所有事件,您只需通过在构造函数中添加 self.label.setDisabled(True) 来禁用标签:Press 事件将限制为 MyLabel 并且它还将接收发布事件。

最新更新