根据禁用状态自动灰显QLineEdit,结合非条件样式表指令?

0 投票
0 回答
23 浏览
提问于 2025-04-11 22:51

默认情况下,当一个 QLineEdit 被禁用时,它会变成灰色,表示不可用。

如果你设置了一个样式表,比如简单地设置一个边框,这样会取消它的默认灰色效果。

幸运的是,我们可以通过一些方法来让它恢复到默认的灰色效果,像这样:

qle.setStyleSheet('QLineEdit[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}')

但是我该如何将这种条件性的灰色效果和设置边框(不管条件如何)结合起来呢?

下面是一个最小可重现示例:

import sys
from PyQt5 import QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QLE stylesheet question")
        self.setMinimumSize(400, 30)
        layout = QtWidgets.QVBoxLayout()
        qle = QtWidgets.QLineEdit()
        qle.setObjectName('qle')
        # qle.setStyleSheet('border:4px solid yellow;')
        # this sets up the style sheet to reproduce the default PyQt behaviour for a QLE (greyed-out if disabled, otherwise not)
        # qle.setStyleSheet('QLineEdit[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}')
        
        # doesn't work: when disabled is not greyed-out!
        qle.setStyleSheet('#qle {border:4px solid yellow;} #qle[readOnly=\"true\"] {color: #808080; background-color: #F0F0F0;}')
        
        # qle.setEnabled(False) # uncomment to see "disabled" appearance
        layout.addWidget(qle)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

0 个回答

暂无回答

撰写回答