PyQt4 - 在继承自QWidget的对象上应用样式表

时间:2017-09-04 00:09:04

标签: python pyqt pyqt4 stylesheet qwidget

我遇到了PyQt4的问题。我有一个继承自QWidget的类。此类使用布局来存储QLabel和QLineEdit。这是代码:

class SearchBar(QtGui.QWidget):
    def __init__(self, parent=None):
        super(SearchBar, self).__init__(parent)
        self.setStyleSheet(SEARCHBAR_STYLE)

        layout = QtGui.QHBoxLayout()
        layout.setSpacing(0)
        layout.setMargin(0)
        layout.addStrut(SEARCHAR_HEIGHT)

        lbl_notification = QtGui.QLabel('Hi')
        lbl_notification.setStyleSheet(SEARCHBAR_NOTIFICATION_STYLE)
        layout.addSpacing(10)
        layout.addWidget(lbl_notification)

        searchbox = QLineEdit('Search')
        layout.addStretch()
        layout.addWidget(searchbox)
        layout.addSpacing(10)

        self.setLayout(layout)

这是样式表:

SEARCHBAR_STYLE = """
                  QWidget {
                      background: #424a7d;
                  }
                  .QWidget {
                      border: 1px solid grey;
                  }
                  QLabel {
                      border-top: 1px solid grey;
                      border-bottom: 1px solid grey;
                  }
                  """

现在,我的问题是样式表不适用我想要的方式。当边框应该围绕整个对象时,它仅适用于我的QLabel:

enter image description here

当我有一个函数创建我的搜索栏作为QWidget时,它工作得很好,但现在我把它改成了一个类它不起作用。我做错了什么?

编辑:我正在努力实现这一目标:

enter image description here

编辑2:之前的代码,在我将其更改为类之前,是:

def create_bar():
    layout = QtGui.QHBoxLayout()
    layout.setSpacing(0)
    layout.setMargin(0)
    layout.addStrut(SEARCHAR_HEIGHT)

    lbl_notification = QtGui.QLabel('Hi')
    lbl_notification.setStyleSheet(SEARCHBAR_NOTIFICATION_STYLE)
    layout.addSpacing(10)
    layout.addWidget(lbl_notification)

    search_bar = QtGui.QLineEdit('Search')
    search_bar.setMinimumSize(200, 25)
    search_bar.setMaximumSize(200, 25)
    search_bar.setStyleSheet(SEARCHBOX_STYLE)

    layout.addStretch()
    layout.addWidget(search_bar)
    layout.addSpacing(10)

    widget = QtGui.QWidget()
    widget.setStyleSheet(SEARCHBAR_STYLE)
    widget.setLayout(layout)
    return widget

1 个答案:

答案 0 :(得分:3)

将SearchBar的基类从QWidget更改为QFrame,或者实现style sheet aware paintEvent

def paintEvent(self, event):
    opt = QStyleOption()
    opt.initFrom(self)
    painter = QPainter(self)
    self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

然后将样式表更改为

SEARCHBAR_STYLE = """
SearchBar {
    background: #424a7d;
    border: 1px solid grey;
}
"""