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

arknldoa  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(266)

我有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);
}
mqkwyuun

mqkwyuun1#

一种可能的解决方案是将动态特性用作选择器:

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

相关问题