【问题标题】:How to emit signal that activates CSS Pseudo-elements?如何发出激活 CSS 伪元素的信号?
【发布时间】:2021-04-08 17:52:45
【问题描述】:

我有定义样式表的 QLineEdit:

QLineEdit {
    font: 10pt "MS Shell Dlg 2";
        border-radius: 10px;
        border: 2px solid rgb(55,55,55);
        color: rgb(255, 255, 255);
        padding-left: 20px;
        padding-right: 20px;
        background-color: rgb(70,70,70);
}
QLineEdit:hover {
        border: 2px solid rgb(85,85,85);
}
QLineEdit:focus{
        border: 2px solid rgb(85, 170, 255);
}
QLineEdit:invalid{
        border: 2px solid rgb(255, 115, 107);
}

当我悬停或关注 QLineEdit 时,它会根据样式表中定义的颜色更改边框。

我怎样才能发出信号或者我应该向 QLineEdit 应用什么状态来激活 invalid 伪元素并更改在 QLineEdit:invalid 块中定义的边框?

我知道我可以这样设置样式表,但我想避免这种解决方案并使用invalidpseudo-element

QLineEdit{
        border: 2px solid rgb(255, 115, 107);
        border-radius: 10px;
        color: rgb(255, 255, 255);
        padding-left: 20px;
        padding-right: 20px;
        background-color: rgb(70,70,70);
}

【问题讨论】:

  • :invalid 不是 Qt 的 recognized pseudo state,所以你不能“触发”它。请记住,Qt 样式表只是 CSS 标准的有限实现(并且仅尊重 CSS2.1),它们不提供 整个 css 实现。

标签: python pyside2 qtstylesheets qlineedit


【解决方案1】:

一种可能的解决方案是使用动态属性作为选择器:

import sys

from PySide2.QtWidgets import QApplication, QLineEdit


class LineEdit(QLineEdit):
    QSS = """
    QLineEdit {
        font: 10pt "MS Shell Dlg 2";
        border-radius: 10px;
        border: 2px solid rgb(55,55,55);
        color: rgb(255, 255, 255);
        padding-left: 20px;
        padding-right: 20px;
        background-color: rgb(70,70,70);
    }
    QLineEdit:hover {
        border: 2px solid rgb(85,85,85);
    }
    QLineEdit:focus{
        border: 2px solid rgb(85, 170, 255);
    }
    QLineEdit[invalid="true"]{
        border: 2px solid rgb(255, 115, 107);
    }"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.textChanged.connect(self._handle_textChanged)
        self.setProperty("invalid", False)
        self.setStyleSheet(self.QSS)
        self._handle_textChanged()

    def _handle_textChanged(self):
        self.setProperty("invalid", not self.isValid())
        self.style().polish(self)

    def isValid(self):
        return len(self.text()) % 2 == 0


def main():
    app = QApplication(sys.argv)
    w = LineEdit()
    w.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

【讨论】:

  • 我实现了我的目标,但我需要稍微修改解决方案:D。非常感谢@eyllanesc
猜你喜欢
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多