Python 不同标签上的不同悬停样式

Python 不同标签上的不同悬停样式,python,python-3.x,pyqt,pyqt5,qtstylesheets,Python,Python 3.x,Pyqt,Pyqt5,Qtstylesheets,我有两个标签(标签1和2),当任何标签悬停在上面时,我希望它们的样式都不同。我怎样才能做到这一点?我在pyqt5中使用css样式。PS:我的两个标签都在我的滚动区域内,因此在样式表中所做的更改在运行时生效。您可以为每个标签设置可访问名称:label.setAccessibleName(“label1”) 并在样式表中将其作为目标,如下所示: self.scrollArea.setStyleSheet("background-color: rgba(255, 0, 0, 0);

我有两个标签(标签1和2),当任何标签悬停在上面时,我希望它们的样式都不同。我怎样才能做到这一点?我在pyqt5中使用css样式。PS:我的两个标签都在我的滚动区域内,因此在样式表中所做的更改在运行时生效。

您可以为每个标签设置可访问名称:
label.setAccessibleName(“label1”)

并在样式表中将其作为目标,如下所示:

    self.scrollArea.setStyleSheet("background-color: rgba(255, 0, 0, 0); border-style:none;\n"
    "}\n"
    "QLabel#label2 {    \n"
    "   background-color: rgba(0, 0, 0, 120); color: white; text: center; border-style:solid; border- 
    width: 1px; border-top-style: none;\n"
    "}\n"
    "QLabel#label3 {    \n"
    "background-color: rgba(0, 0, 0, 0); color: rgba(255, 255, 255, 0); text: center;\n"
    "}\n"
    "QLabel:hover + QLabel#label2{  \n"
    "background-color: rgb(0, 0, 0, 120); color: rgba(255,255,255,255); text: center;\n"
    "}\n"
    "QLabel:hover + QLabel#label3 { \n"
    "background-color: rgb(118, 185, 0); color: rgba(255,255,255,255); text: center;\n"
    "}\n")
QLabel[accessibleName="label1"]{ border: 1px solid red;}
您还可以为特定的小部件设置样式表,如下所示:

    self.scrollArea.setStyleSheet("background-color: rgba(255, 0, 0, 0); border-style:none;\n"
    "}\n"
    "QLabel#label2 {    \n"
    "   background-color: rgba(0, 0, 0, 120); color: white; text: center; border-style:solid; border- 
    width: 1px; border-top-style: none;\n"
    "}\n"
    "QLabel#label3 {    \n"
    "background-color: rgba(0, 0, 0, 0); color: rgba(255, 255, 255, 0); text: center;\n"
    "}\n"
    "QLabel:hover + QLabel#label2{  \n"
    "background-color: rgb(0, 0, 0, 120); color: rgba(255,255,255,255); text: center;\n"
    "}\n"
    "QLabel:hover + QLabel#label3 { \n"
    "background-color: rgb(118, 185, 0); color: rgba(255,255,255,255); text: center;\n"
    "}\n")
QLabel[accessibleName="label1"]{ border: 1px solid red;}
此外,我建议对多行字符串使用三重引号:

widget.setStyleSheet('QLabel:hover{border:1px solid red;}')

这确实可以让悬停单独工作,但我希望这样,当鼠标悬停在一个标签悬停效果上时,两个标签悬停效果都会被激活。这是可能的还是有办法做到这一点?问题是两个标签都有不同的悬停效果,但如果其中一个是,我需要它们都被激活。不过还是要谢谢你,因为它确实帮助我清理了样式表。或者我误解了,这确实让我这么做了,因为当我尝试时,这两个都没有激活。看起来我误解了你的问题,但你想要的是鼠标悬停在标签上时的信号。我很确定QLabel类没有这样的信号。您可以查看eventFilters并捕获MouseMove事件。看看这篇文章是否能指导你。请更清楚你的要求;2.尝试以更易读的方式格式化代码:我建议您对这样的字符串使用三重引号(
''textotherthext'
);3.如中所述,QLabel不支持
:hover
伪状态,因此您必须通过对标签进行子类化、安装事件过滤器、小部件对其进行升级,或者最终对标签进行猴子补丁来实现它。