Search code examples
pythonpyside2qtstylesheetsqlineedit

How to emit signal that activates CSS Pseudo-elements?


I have QLineEdit with defined stylesheet:

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

When I hover or focus on that QLineEdit, it changes border according to defined color in stylesheet.

How can I emit signal or what state should I apply to QLineEdit to activate invalid pseudo-element and change border defined in QLineEdit:invalid block?

I know that I can set stylesheet like this, but I want to avoid this solution and use invalid pseudo-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);
}

Solution

  • One possible solution is to use the dynamic properties as a selector:

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