如何发出激活 CSS 伪元素的信号?

How to emit signal that activates CSS Pseudo-elements?

我有带有已定义样式表的 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 块中定义的边框?

我知道我可以像这样设置样式表,但我想避免这种解决方案并使用 invalid 伪元素

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);
}

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

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()