PyQt4 - 在从QWidget继承的对象上应用样式表
问题描述:
我遇到了PyQt4的问题。我有一个从QWidget继承的类。该类使用布局来存储QLabel和QLineEdit。下面是代码:PyQt4 - 在从QWidget继承的对象上应用样式表
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当边界应该在整个对象:
当我有一个函数创建我的搜索栏作为一个QWidget,它的工作完美,但现在我改变了一个它不起作用。我究竟做错了什么?
编辑:我试图做到这一点:
编辑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
答
换基从QWidget到QFrame的SearchBar类,或者实现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;
}
"""
什么是'SearchBox'? – eyllanesc
当你说以下内容时:**将其改为一堂课**,你的意思是? – eyllanesc
@eyllanesc SearchBox是继承QLineEdit并具有一些覆盖函数以适应我的需求的类。我没有把它放在问题上,因为我不认为它与我的问题有关 –