【问题标题】:PyQt5 Stylesheet For QWidget's Child To Change QWidgetPyQt5 样式表用于 QWidget 的孩子更改 QWidget
【发布时间】:2020-02-26 12:08:57
【问题描述】:

我有一个QWidget,里面有一个HBoxLayout。在这个HBoxLayout 里面有几个按钮和一个QLineEdit 对象。使用样式表,我想使 QLineEdit 聚焦时,QWidget 获得蓝色轮廓/边框。

我试过了:

QSearchWidgetStyleSheet = QWidget {background-color: rgb(27,27,27); border: none; margin: 0px; border-radius: 3px; padding: 0px;}
                          QLineEdit:focus {border: 3px solid rgb(100,100,100;}

我的QLineEdit 样式表是:

QLineEditStyleSheet = QLineEdit {color: white; background-color: rgb(255,255,255,0); border: none; height: 32px; border-radius: 3px; margin-left: 3px; margin-right: 3px;}

但是,当QLineEdit 被聚焦时,QWidget 没有任何影响。当QLineEdit 聚焦时,我应该更改什么以使QWidget 获得边框/轮廓?

【问题讨论】:

    标签: pyqt5 children qtstylesheets


    【解决方案1】:

    QLineEdit:focus 将样式应用于 QLineEdit,而不是 QWidget。虽然子小部件可以占用其父小部件的样式表,但我认为在一般样式表语法中它不会以相反的方式工作。相反,您可以仅考虑 QWidget 来描述该场景...它在未聚焦时应该有边框,并且在聚焦时不应该有边框。

    import sys
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    
    class Widget(QWidget):
    
        def __init__(self):
            super().__init__()
            hbox = QHBoxLayout(self)
            hbox.addWidget(QPushButton('Push'))
            hbox.addWidget(QLineEdit())
            self.setAttribute(Qt.WA_StyledBackground, True)
            self.setStyleSheet('''
            Widget {
                border: 3px solid blue;
            }
            Widget:focus {
                border: none;
            }''')
    
        def mousePressEvent(self, event):
            if event.button() == Qt.LeftButton:
                self.setFocus()
    
    
    class Template(QWidget):
    
        def __init__(self):
            super().__init__()
            grid = QGridLayout(self)
            grid.addWidget(Widget(), 0, 0)
            self.resize(300, 300)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        gui = Template()
        gui.show()
        sys.exit(app.exec_())
    

    当然,如果您愿意使用其他方法,例如信号和插槽,您可以更精确地实现该功能。

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多